브리지 모드 예

2339 단어 디자인 모드
적용 장면: 한 종 류 는 두 개의 독립 적 인 변화 차원 이 필요 하고 두 차원 모두 확장 이 필요 합 니 다.
예: 도형 에 색칠
/**
 * Created by Administrator on 2018-10-20.
 */
public abstract class Shape {
    Color color;

    Shape(Color color) {
        this.color = color;
    }

    protected abstract void draw();

}
/**
 * Created by Administrator on 2018-10-20.
 */
public class Circle extends Shape {


    public Circle(Color color) {
        super(color);
    }

    @Override
    protected void draw() {
        color.paint("  ");
    }
}
/**
 * Created by Administrator on 2018-10-20.
 */
public class Rectangle extends Shape {


    public Rectangle(Color color) {
        super(color);
    }

    @Override
    protected void draw() {
        color.paint("   ");
    }
}
/**
 * Created by Administrator on 2018-10-20.
 */
public class Square extends Shape {


    public Square(Color color) {
        super(color);
    }

    @Override
    protected void draw() {
        color.paint("   ");
    }
}
/**
 * Created by Administrator on 2018-10-20.
 */
public interface Color {
    public void paint(String shape);
}
/**
 * Created by Administrator on 2018-10-20.
 */
public class Red implements Color {
    @Override
    public void paint(String shape) {
        System.out.println("   " + shape);
    }
}
public class Blue implements Color {
    @Override
    public void paint(String shape) {
        System.out.println("   " + shape);
    }
}
/**
 * Created by Administrator on 2018-10-20.
 */
public class Yellow implements Color{
    @Override
    public void paint(String shape) {
        System.out.println("   "+shape);
    }
}
/**
 *               ,          
 *                    
 * 1.       
 * 2.            
 * Created by Administrator on 2018-10-20.
 */
public class Client {
    public static void main(String[] args) {
        //    
        Color color = new Red();
        Shape circle = new Circle(color);
        circle.draw();

        //     
        Color yellow = new Yellow();
        Shape rectangle = new Rectangle(yellow);
        rectangle.draw();
    }
}

좋은 웹페이지 즐겨찾기