[Thực hành] Triển khai Proxy

NỘI DUNG BÀI VIẾT

Mục tiêu

Luyện tập sử dụng Proxy Pattern.

Mô tả

Trong phần này, chúng ta sẽ phát triển một ứng dụng tính toán đơn giản, trong đó lớp MathCalculator thực hiện các phép tính toán. Nhưng chúng ta muốn kiểm tra các điều kiện hợp lệ trước khi thực hiện các phép tính toán, do đó chúng ta tạo thêm lớp MathCalculatorProxy để thực hiện các thao tác kiểm tra.

Hướng dẫn

Bước 1: Tạo Interface Calculator

public interface Calculator {
double add(double first, double second);
double sub(double first, double second);
double mul(double first, double second);
double div(double first, double second);
}

Bước 2: Tạo lớp MathCalculator

public class MathCalculator implements Calculator {

@Override
public double add(double first, double second) {
return first + second;
}

@Override
public double sub(double first, double second) {
return first - second;
}

@Override
public double mul(double first, double second) {
return first * second;
}

@Override
public double div(double first, double second) {
return first / second;
}
}

Bước 3: Tạo lớp MathCalculatorProxy

public class MathCalculatorProxy implements Calculator {
private MathCalculator mathCalculator;

public MathCalculatorProxy(){
this.mathCalculator = new MathCalculator();
}

@Override
public double add(double first, double second) {
if(first / 2 + second / 2 >= Double.MAX_VALUE / 2){
throw new RuntimeException("Out of range");
}
if(first / 2 + second / 2 <= Double.MIN_VALUE / 2){
throw new RuntimeException("Out of range");
}
return mathCalculator.add(first, second);
}

@Override
public double sub(double first, double second) {
if(first / 2 - second / 2 >= Double.MAX_VALUE / 2){
throw new RuntimeException("Out of range");
}
if(first / 2 - second / 2 <= Double.MIN_VALUE / 2){
throw new RuntimeException("Out of range");
}
return mathCalculator.sub(first, second);
}

@Override
public double mul(double first, double second) {
double result = mathCalculator.mul(first, second);
if(first != 0 && result / first != second){
throw new RuntimeException("Out of range");
}
return result;
}

@Override
public double div(double first, double second) {
if(second == 0){
throw new RuntimeException("Can't divide by zero");
}
return mathCalculator.div(first, second);
}
}

Bước 4: Chạy ứng dụng

public class Main {

public static void main(String[] args) {
MathCalculatorProxy proxy = new MathCalculatorProxy();
double result = proxy.add(1, 2);
System.out.println("1 + 2 = " + result);
result = proxy.add(2, Double.MAX_VALUE);
System.out.println("2 + Double.MAX_VALUE = " + result);//Should throw exception
}
}

Với trường hợp thứ 2, thì một ngoại lệ được tung ra, nhờ việc MathCalculatorProxy đã kiểm tra điều kiện của các tham số trước đó.

Bài viết liên quan

Trả lời

Email của bạn sẽ không được hiển thị công khai.

Tài liệu + Khóa học lập trình FREE
Tài liệu + Khóa học lập trình FREE

DMCA.com Protection Status