设计模式——桥接模式

实现不同人、不同画笔、不同颜料三个类别的桥接

//把笔抽象出来
abstract class Brush {
    protected Color c;
    protected Person p;
    //不同的笔和颜色有不同的实现方式,因此各自重写抽象方法。
    public abstract void paint();
    //颜色不需要抽象出来,它通过多态实现即可。
    public void setColor(Color c) {
        this.c = c;
    }
    public void setPerson(Person p){
        this.p = p;
    }
}

class BigBrush extends Brush {
    @Override
    public void paint() {
        System.out.println(p.person + " use big brush paint " + c.color);
    }
}

class SmallBrush extends Brush {
    @Override
    public void paint() {
        System.out.println(p.person + " use small brush paint " + c.color);
    }
}
//把颜色抽象出来
abstract class Color {
    public String color;
}

class Red extends Color{
    public Red(){
        this.color = "red";
    }
}

class Green extends Color{
    public Green(){
        this.color = "green";
    }
}

class Blue extends Color{
    public Blue(){
        this.color = "blue";
    }
}
abstract class Person {
    public String person;
}

class Man extends Person{
    public Man(){
        this.person = "man";
    }
}

class Woman extends Person{
    public Woman(){
        this.person = "woman";
    }
}
/*
三个类别的桥接。降低耦合度
 */
public class Client {
    public static void main(String[] args) {
        //new一个大的笔
        Brush brush = new BigBrush();
        brush.setColor(new Red());
        brush.setPerson(new Man());
        brush.paint();
        brush.setColor(new Green());
        brush.setPerson(new Woman());
        brush.paint();
        //new一个小的笔
        Brush brush1 = new SmallBrush();
        brush1.setColor(new Blue());
        brush1.setPerson(new Woman());
        brush1.paint();
    }
}

输出

man use big brush paint red
woman use big brush paint green
woman use small brush paint blue
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值