Tôi sẽ tạo một » ImageProcesssor « (hoặc bất kỳ tên nào phù hợp với dự án của bạn) và một đối tượng cấu hình ProcessConfiguration , chứa tất cả các tham số cần thiết.
ImageProcessor p = new ImageProcessor();
ProcessConfiguration config = new processConfiguration().setTranslateX(100)
.setTranslateY(100)
.setRotationAngle(45);
p.process(image, config);
Bên trong bộ xử lý hình ảnh, bạn gói gọn toàn bộ quá trình đằng sau một mehtod process()
public class ImageProcessor {
public Image process(Image i, ProcessConfiguration c){
Image processedImage=i.getCopy();
shift(processedImage, c);
rotate(processedImage, c);
return processedImage;
}
private void rotate(Image i, ProcessConfiguration c) {
//rotate
}
private void shift(Image i, ProcessConfiguration c) {
//shift
}
}
Phương thức này gọi các phương thức biến đổi theo đúng thứ tự shift(), rotate(). Mỗi phương thức nhận các tham số thích hợp từ ProcessConfiguration được thông qua .
public class ProcessConfiguration {
private int translateX;
private int rotationAngle;
public int getRotationAngle() {
return rotationAngle;
}
public ProcessConfiguration setRotationAngle(int rotationAngle){
this.rotationAngle=rotationAngle;
return this;
}
public int getTranslateY() {
return translateY;
}
public ProcessConfiguration setTranslateY(int translateY) {
this.translateY = translateY;
return this;
}
public int getTranslateX() {
return translateX;
}
public ProcessConfiguration setTranslateX(int translateX) {
this.translateX = translateX;
return this;
}
private int translateY;
}
Tôi đã sử dụng giao diện chất lỏng
public ProcessConfiguration setRotationAngle(int rotationAngle){
this.rotationAngle=rotationAngle;
return this;
}
cho phép khởi tạo tiện lợi (như đã thấy ở trên).
Lợi thế rõ ràng, gói gọn các tham số cần thiết trong một đối tượng. Chữ ký phương thức của bạn trở nên dễ đọc:
private void shift(Image i, ProcessConfiguration c)
Đó là về việc dịch chuyển một hình ảnh và các thông số chi tiết được cấu hình bằng cách nào đó .
Ngoài ra, bạn có thể tạo một Chế độ xử lý :
public class ProcessingPipeLine {
Image i;
public ProcessingPipeLine(Image i){
this.i=i;
};
public ProcessingPipeLine shift(Coordinates c){
shiftImage(c);
return this;
}
public ProcessingPipeLine rotate(int a){
rotateImage(a);
return this;
}
public Image getResultingImage(){
return i;
}
private void rotateImage(int angle) {
//shift
}
private void shiftImage(Coordinates c) {
//shift
}
}
Một cuộc gọi phương thức đến một phương thức processImagesẽ khởi tạo một đường ống như vậy và minh bạch hóa những gì và theo thứ tự được thực hiện: thay đổi , xoay
public Image processImage(Image i, ProcessConfiguration c){
Image processedImage=i.getCopy();
processedImage=new ProcessingPipeLine(processedImage)
.shift(c.getCoordinates())
.rotate(c.getRotationAngle())
.getResultingImage();
return processedImage;
}