美文网首页
设计模式(第二类:结构型 包含例子)

设计模式(第二类:结构型 包含例子)

作者: momxmo | 来源:发表于2020-07-02 15:07 被阅读0次

    二、结构型

    2.1 适配器

    意图:将一个类的接口转换成客户希望的另外一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
    使用场景:
    有动机地修改一个正常运行的系统的接口,这时应该考虑使用适配器模式。
    实现:

    步骤 1
    //为媒体播放器和更高级的媒体播放器创建接口。
    public interface MediaPlayer {
       public void play(String audioType, String fileName);
    }
    public interface AdvancedMediaPlayer { 
       public void playVlc(String fileName);
       public void playMp4(String fileName);
    }
    步骤 2
    //创建实现了 AdvancedMediaPlayer 接口的实体类。
    public class VlcPlayer implements AdvancedMediaPlayer{
       @Override
       public void playVlc(String fileName) {
          System.out.println("Playing vlc file. Name: "+ fileName);      
       }
       @Override
       public void playMp4(String fileName) {
          //什么也不做
       }
    }
    public class Mp4Player implements AdvancedMediaPlayer{
     
       @Override
       public void playVlc(String fileName) {
          //什么也不做
       }
     
       @Override
       public void playMp4(String fileName) {
          System.out.println("Playing mp4 file. Name: "+ fileName);      
       }
    }
    步骤 3
    //创建实现了 MediaPlayer 接口的适配器类。
    public class MediaAdapter implements MediaPlayer {
       AdvancedMediaPlayer advancedMusicPlayer;
       public MediaAdapter(String audioType){
          if(audioType.equalsIgnoreCase("vlc") ){
             advancedMusicPlayer = new VlcPlayer();       
          } else if (audioType.equalsIgnoreCase("mp4")){
             advancedMusicPlayer = new Mp4Player();
          }  
       }
       @Override
       public void play(String audioType, String fileName) {
          if(audioType.equalsIgnoreCase("vlc")){
             advancedMusicPlayer.playVlc(fileName);
          }else if(audioType.equalsIgnoreCase("mp4")){
             advancedMusicPlayer.playMp4(fileName);
          }
       }
    }
    步骤 4
    //创建实现了 MediaPlayer 接口的实体类。
    public class AudioPlayer implements MediaPlayer {
       MediaAdapter mediaAdapter; 
     
       @Override
       public void play(String audioType, String fileName) {    
     
          //播放 mp3 音乐文件的内置支持
          if(audioType.equalsIgnoreCase("mp3")){
             System.out.println("Playing mp3 file. Name: "+ fileName);         
          } 
          //mediaAdapter 提供了播放其他文件格式的支持
          else if(audioType.equalsIgnoreCase("vlc") 
             || audioType.equalsIgnoreCase("mp4")){
             mediaAdapter = new MediaAdapter(audioType);
             mediaAdapter.play(audioType, fileName);
          }
          else{
             System.out.println("Invalid media. "+
                audioType + " format not supported");
          }
       }   
    }
    步骤 5
    //使用 AudioPlayer 来播放不同类型的音频格式。
    public class AdapterPatternDemo {
       public static void main(String[] args) {
          AudioPlayer audioPlayer = new AudioPlayer();
     
          audioPlayer.play("mp3", "beyond the horizon.mp3");
          audioPlayer.play("mp4", "alone.mp4");
          audioPlayer.play("vlc", "far far away.vlc");
          audioPlayer.play("avi", "mind me.avi");
       }
    }
    
    
    2.2 桥接

    意图:将抽象部分与实现部分分离,使它们都可以独立的变化。
    使用场景:
    1、如果一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性,避免在两个层次之间建立静态的继承联系,通过桥接模式可以使它们在抽象层建立一个关联关系。
    2、对于那些不希望使用继承或因为多层次继承导致系统类的个数急剧增加的系统,桥接模式尤为适用。
    3、一个类存在两个独立变化的维度,且这两个维度都需要进行扩展。
    实现:

    步骤 1
    //创建桥接实现接口。
    public interface DrawAPI {
       public void drawCircle(int radius, int x, int y);
    }
    步骤 2
    //创建实现了 DrawAPI 接口的实体桥接实现类。
    public class RedCircle implements DrawAPI {
       @Override
       public void drawCircle(int radius, int x, int y) {
          System.out.println("Drawing Circle[ color: red, radius: "
             + radius +", x: " +x+", "+ y +"]");
       }
    }
    public class GreenCircle implements DrawAPI {
       @Override
       public void drawCircle(int radius, int x, int y) {
          System.out.println("Drawing Circle[ color: green, radius: "
             + radius +", x: " +x+", "+ y +"]");
       }
    }
    步骤 3
    //使用 DrawAPI 接口创建抽象类 Shape。
    public abstract class Shape {
       protected DrawAPI drawAPI;
       protected Shape(DrawAPI drawAPI){
          this.drawAPI = drawAPI;
       }
       public abstract void draw();  
    }
    步骤 4
    //创建实现了 Shape 接口的实体类。
    public class Circle extends Shape {
       private int x, y, radius;
     
       public Circle(int x, int y, int radius, DrawAPI drawAPI) {
          super(drawAPI);
          this.x = x;  
          this.y = y;  
          this.radius = radius;
       }
    
       public void draw() {
          drawAPI.drawCircle(radius,x,y);
       }
    }
    步骤 5
    //使用 Shape 和 DrawAPI 类画出不同颜色的圆。
    public class BridgePatternDemo {
       public static void main(String[] args) {
          Shape redCircle = new Circle(100,100, 10, new RedCircle());
          Shape greenCircle = new Circle(100,100, 10, new GreenCircle());
     
          redCircle.draw();
          greenCircle.draw();
       }
    }
    
    2.3 组合

    意图:将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
    使用场景:
    部分、整体场景,如树形菜单,文件、文件夹的管理。
    实现:

    步骤 1
    //创建 Employee 类,该类带有 Employee 对象的列表。
    public class Employee {
       private String name;
       private String dept;
       private int salary;
       private List<Employee> subordinates;
       //构造函数
       public Employee(String name,String dept, int sal) {
          this.name = name;
          this.dept = dept;
          this.salary = sal;
          subordinates = new ArrayList<Employee>();
       }
       public void add(Employee e) {
          subordinates.add(e);
       }
       public void remove(Employee e) {
          subordinates.remove(e);
       }
       public List<Employee> getSubordinates(){
         return subordinates;
       }
       public String toString(){
          return ("Employee :[ Name : "+ name 
          +", dept : "+ dept + ", salary :"
          + salary+" ]");
       }   
    }
    步骤 2
    //使用 Employee 类来创建和打印员工的层次结构。
    public class CompositePatternDemo {
       public static void main(String[] args) {
          Employee CEO = new Employee("John","CEO", 30000);
     
          Employee headSales = new Employee("Robert","Head Sales", 20000);
     
          Employee headMarketing = new Employee("Michel","Head Marketing", 20000);
     
          Employee clerk1 = new Employee("Laura","Marketing", 10000);
          Employee clerk2 = new Employee("Bob","Marketing", 10000);
     
          Employee salesExecutive1 = new Employee("Richard","Sales", 10000);
          Employee salesExecutive2 = new Employee("Rob","Sales", 10000);
     
          CEO.add(headSales);
          CEO.add(headMarketing);
     
          headSales.add(salesExecutive1);
          headSales.add(salesExecutive2);
     
          headMarketing.add(clerk1);
          headMarketing.add(clerk2);
     
          //打印该组织的所有员工
          System.out.println(CEO); 
          for (Employee headEmployee : CEO.getSubordinates()) {
             System.out.println(headEmployee);
             for (Employee employee : headEmployee.getSubordinates()) {
                System.out.println(employee);
             }
          }        
       }
    }
    
    2.4 装饰

    意图:动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活。
    使用场景:
    1、扩展一个类的功能。
    2、动态增加功能,动态撤销。
    实现:

    步骤 1
    //创建一个接口:
    public interface Shape {
       void draw();
    }
    步骤 2
    //创建实现接口的实体类。
    public class Rectangle implements Shape {
       @Override
       public void draw() {
          System.out.println("Shape: Rectangle");
       }
    }
    public class Circle implements Shape {
       @Override
       public void draw() {
          System.out.println("Shape: Circle");
       }
    }
    步骤 3
    //创建实现了 Shape 接口的抽象装饰类。
    public abstract class ShapeDecorator implements Shape {
       protected Shape decoratedShape;
       public ShapeDecorator(Shape decoratedShape){
          this.decoratedShape = decoratedShape;
       }
       public void draw(){
          decoratedShape.draw();
       }  
    }
    步骤 4
    //创建扩展了 ShapeDecorator 类的实体装饰类。
    public class RedShapeDecorator extends ShapeDecorator {
       public RedShapeDecorator(Shape decoratedShape) {
          super(decoratedShape);     
       }
       @Override
       public void draw() {
          decoratedShape.draw();         
          setRedBorder(decoratedShape);
       }
       private void setRedBorder(Shape decoratedShape){
          System.out.println("Border Color: Red");
       }
    }
    步骤 5
    //使用 RedShapeDecorator 来装饰 Shape 对象。
    public class DecoratorPatternDemo {
       public static void main(String[] args) {
     
          Shape circle = new Circle();
          ShapeDecorator redCircle = new RedShapeDecorator(new Circle());
          ShapeDecorator redRectangle = new RedShapeDecorator(new Rectangle());
          //Shape redCircle = new RedShapeDecorator(new Circle());
          //Shape redRectangle = new RedShapeDecorator(new Rectangle());
          System.out.println("Circle with normal border");
          circle.draw();
     
          System.out.println("\nCircle of red border");
          redCircle.draw();
     
          System.out.println("\nRectangle of red border");
          redRectangle.draw();
       }
    }
    
    
    2.5 外观

    意图:为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
    使用场景:
    1、为复杂的模块或子系统提供外界访问的模块。
    2、子系统相对独立。
    3、预防低水平人员带来的风险。
    实现:

    步骤 1
    //创建一个接口。
    public interface Shape {
       void draw();
    }
    步骤 2
    //创建实现接口的实体类。
    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()");
       }
    }
    步骤 3
    //创建一个外观类。
    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();
       }
    }
    步骤 4
    //使用该外观类画出各种类型的形状。
    public class FacadePatternDemo {
       public static void main(String[] args) {
          ShapeMaker shapeMaker = new ShapeMaker();
     
          shapeMaker.drawCircle();
          shapeMaker.drawRectangle();
          shapeMaker.drawSquare();      
       }
    }
    
    
    
    
    2.6 享元

    意图:运用共享技术有效地支持大量细粒度的对象。
    使用场景:
    1、系统有大量相似对象。
    2、需要缓冲池的场景。
    实现:

    步骤 1
    //创建一个接口。
    public interface Shape {
       void draw();
    }
    步骤 2
    //创建实现接口的实体类。
    public class Circle implements Shape {
       private String color;
       private int x;
       private int y;
       private int radius;
       public Circle(String color){
          this.color = color;     
       }
       public void setX(int x) {
          this.x = x;
       }
       public void setY(int y) {
          this.y = y;
       }
       public void setRadius(int radius) {
          this.radius = radius;
       }
       @Override
       public void draw() {
          System.out.println("Circle: Draw() [Color : " + color 
             +", x : " + x +", y :" + y +", radius :" + radius);
       }
    }
    步骤 3
    //创建一个工厂,生成基于给定信息的实体类的对象。
    public class ShapeFactory {
       private static final HashMap<String, Shape> circleMap = new HashMap<>();
       public static Shape getCircle(String color) {
          Circle circle = (Circle)circleMap.get(color);
     
          if(circle == null) {
             circle = new Circle(color);
             circleMap.put(color, circle);
             System.out.println("Creating circle of color : " + color);
          }
          return circle;
       }
    }
    步骤 4
    //使用该工厂,通过传递颜色信息来获取实体类的对象。
    public class FlyweightPatternDemo {
       private static final String colors[] = 
          { "Red", "Green", "Blue", "White", "Black" };
       public static void main(String[] args) {
     
          for(int i=0; i < 20; ++i) {
             Circle circle = 
                (Circle)ShapeFactory.getCircle(getRandomColor());
             circle.setX(getRandomX());
             circle.setY(getRandomY());
             circle.setRadius(100);
             circle.draw();
          }
       }
       private static String getRandomColor() {
          return colors[(int)(Math.random()*colors.length)];
       }
       private static int getRandomX() {
          return (int)(Math.random()*100 );
       }
       private static int getRandomY() {
          return (int)(Math.random()*100);
       }
    }
    
    
    2.7 代理

    意图:为其他对象提供一种代理以控制对这个对象的访问。
    使用场景:
    按职责来划分,通常有以下使用场景:
    1、远程代理。
    2、虚拟代理。
    3、Copy-on-Write 代理。
    4、保护(Protect or Access)代理。
    5、Cache代理。
    6、防火墙(Firewall)代理。
    7、同步化(Synchronization)代理。
    8、智能引用(Smart Reference)代理。

    实现:

    步骤 1
    //创建一个接口。
    public interface Image {
       void display();
    }
    步骤 2
    //创建实现接口的实体类。
    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();
       }
    }
    步骤 3
    //当被请求时,使用 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();  
       }
    }
    
    
    

    相关文章

      网友评论

          本文标题:设计模式(第二类:结构型 包含例子)

          本文链接:https://www.haomeiwen.com/subject/ejuhqktx.html