桥接模式 -- 设计模式
桥接(Bridge)是用于把抽象化与实现化解耦,使得二者可以独立变化。
思考: 其实就是把实现化的部分独立出来作为接口给其他类来实现, 然后通过use的关系来完成实现化的多样化, 使用红色的API就是红色的, 使用绿色的API就是绿色的
package day0317.BridgePattern; import java.util.Scanner; public class BridgePatternDemo{ public static void main(String[] args){ Circle redCircle = new Circle(0, 0, 10, new RedCircle()); System.out.println(redCircle.draw()); } } abstract class Shape{ protected DrawAPI drawAPI; public Shape(DrawAPI drawAPI){ this.drawAPI = drawAPI; } abstract String draw(); } class Circle extends Shape { int x, y, radius; public Circle(int x, int y, int z, DrawAPI drawAPI){ super(drawAPI); } @Override String draw(){ return super.drawAPI.drawCircle(this.x, this.y, this.radius); } } interface DrawAPI{ String drawCircle(int x, int y, int radius); } class RedCircle implements DrawAPI{ @Override public String drawCircle(int x, int y, int radius){ return String.format("Drawing a cirle(%s, %s, radius: %s), filling with red color%n", x, y, radius); } } class GreenCircle implements DrawAPI{ @Override public String drawCircle(int x, int y, int radius){ return String.format("Drawing a cirle(%s, %s, radius: %s), filling with green color%n", x, y, radius); } } class BissnessDemo{ } interface Gang { void killPeople(); } class DragonBang implements Gang{ @Override public void killPeople(){ System.out.println("use knife kill people"); } } class TigerBang implements Gang{ @Override public void killPeople(){ System.out.println("use axe kill people"); } } abstract class AbstractBissness { Gang gang; abstract void killPeople(); } class GuangMingCorp extends AbstractBissness{ @Override void killPeople(){ System.out.println("你接受100万的拆迁费吗?"); Scanner scanner = new Scanner(System.in); String anwser = scanner.next(); if ("yes".equalsIgnoreCase(anwser)) { return; } else { super.gang.killPeople(); } } } class HeiAnCorp extends AbstractBissness{ @Override void killPeople(){ System.out.println("你给不给我一百万?"); Scanner scanner = new Scanner(System.in); String anwser = scanner.next(); if ("yes".equalsIgnoreCase(anwser)) { return; } else { super.gang.killPeople(); } } }