设计模式结构型模式——桥接模式

https://www.cnblogs.com/chenssy/p/3317866.html

模式的定义

桥接模式(Bridge Pattern:将抽象部分与它的实现部分分离,使它们都可以独立的变化。

模式的结构

  Abstraction:抽象类。 
  RefinedAbstraction:扩充抽象类。 
  Implementor:实现类接口。 
  ConcreteImplementor:具体实现类 。 

模式的实现

抽象类Shape.java ,主要提供画形状的方法

public abstract class Shape {
    protected DrawAPI drawAPI;
    protected Shape(DrawAPI drawAPI){
        this.drawAPI = drawAPI;
    }

    public abstract void draw();

}

扩充抽象类Circle.java,圆形

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);
    }

}

实现类接口DrawAPI.java

public interface DrawAPI {

    public void drawCircle(int radius,int x,int y);
}

具体实现类GreenCircle.java

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 +"]");
    }
}

具体实现类RedCircle.java

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 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();
    }
}

运行结果

(声明:本文为个人学习笔记,观点非原创。如有问题,欢迎讨论。) 

你可能感兴趣的:(设计模式)