1.外观模式实现逻辑:为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
代码实现:
① 创建一个接口:
public interface Shape { void draw(); }② 创建实现几口的实体类
public class Rectangle implements Shape { @Override public void draw() { System.out.println("Rectangle::draw()"); } }
public class Square implements Shape { @Override public void draw() { System.out.println("Square::draw()"); } }
public class Circle implements Shape { @Override public void draw() { System.out.println("Circle::draw()"); } }
③ 创建一个外观类
public class ShapeMaker { private Shape circle; private Shape rectangle; private Shape square; public ShapeMaker() { circle = new Circle(); rectangle = new Rectangle(); square = new Square(); } public void drawCircle(){ circle.draw(); } public void drawRectangle(){ rectangle.draw(); } public void drawSquare(){ square.draw(); } }④使用该外观类画出各种类型的形状
public class FacadePatternDemo { public static void main(String[] args) { ShapeMaker shapeMaker = new ShapeMaker(); shapeMaker.drawCircle(); shapeMaker.drawRectangle(); shapeMaker.drawSquare(); } }
⑤ 执行程序,输出结果
Circle::draw() Rectangle::draw() Square::draw()2.代理模式实现逻辑:为其他对象提供一种代理以控制对这个对象的访问。
代码实现:
① 创建一个接口
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(); } }③ 当被请求时,使用ProxyImage类获取RealImage类的对象
public class ProxyPatternDemo { public static void main(String[] args) { Image image = new ProxyImage("test_10mb.jpg"); // 图像将从磁盘加载 image.display(); System.out.println(""); // 图像不需要从磁盘加载 image.display(); } }④ 执行程序,输出结果
Loading test_10mb.jpg Displaying test_10mb.jpg Displaying test_10mb.jpg