Java工廠模式是一種創建型設計模式,它定義了一個用于創建對象的接口,但是讓子類來決定實例化哪個類。其實現思路是將所要創建的對象放在一個工廠類中,由工廠類負責生產實例,這樣一來,客戶端只需要知道工廠類的接口就可以獲得所需的對象,而不需要知道具體的實現細節。
public interface Shape { void draw(); } public class Rectangle implements Shape { @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } } public class Square implements Shape { @Override public void draw() { System.out.println("Inside Square::draw() method."); } } public class ShapeFactory { public Shape getShape(String shapeType){ if(shapeType == null){ return null; } if(shapeType.equalsIgnoreCase("CIRCLE")){ return new Circle(); }else if(shapeType.equalsIgnoreCase("RECTANGLE")){ return new Rectangle(); }else if(shapeType.equalsIgnoreCase("SQUARE")){ return new Square(); } return null; } } public class FactoryPatternDemo { public static void main(String[] args) { ShapeFactory shapeFactory = new ShapeFactory(); //獲取形狀為圓形的對象 Shape shape1 = shapeFactory.getShape("CIRCLE"); //調用Circle的draw方法 shape1.draw(); //獲取形狀為長方形的對象 Shape shape2 = shapeFactory.getShape("RECTANGLE"); //調用Rectangle的draw方法 shape2.draw(); //獲取形狀為正方形的對象 Shape shape3 = shapeFactory.getShape("SQUARE"); //調用Square的draw方法 shape3.draw(); } }
Java代理模式是一種結構型設計模式,它允許對象在不暴露自己的情況下,控制其它對象的訪問。代理可以對請求進行過濾和轉發,以及在訪問對象時添加必要的附加操作。代理模式通常用于提供對對象的訪問控制,于是即使用戶沒權限訪問對象也可在代理對象中控制用戶對該對象的訪問。
public interface Image { void display(); } public class RealImage implements Image { private String fileName; public RealImage(String fileName){ this.fileName = fileName; loadFromDisk(fileName); } @Override public void display() { System.out.println("Displaying " + fileName); } private void loadFromDisk(String fileName){ System.out.println("Loading " + fileName); } } public class ProxyImage implements Image{ private RealImage realImage; private String fileName; public ProxyImage(String fileName){ this.fileName = fileName; } @Override public void display() { if(realImage == null){ realImage = new RealImage(fileName); } realImage.display(); } } public class ProxyPatternDemo { public static void main(String[] args) { Image image = new ProxyImage("test.jpg"); //圖像從磁盤加載 image.display(); //圖像不需要從磁盤加載 image.display(); } }