美文网首页
装饰模式

装饰模式

作者: 请叫我平爷 | 来源:发表于2022-03-31 10:11 被阅读0次

拿穿衣服来举例

实现

具体的人

public class People {

    private String name;

    public People(){}

    public People(String name){
        this.name = name;
    }

    public void show(){
        System.out.println("装扮人是:"+this.name);
    }

}

衣服

public class Cloth extends People{

    private People people;

    public Cloth(People people){
        this.people = people;
    }

    @Override
    public void show() {
        people.show();
    }
}

长袖

public class Sleeves extends Cloth{

    public Sleeves(People people) {
        super(people);
    }

    @Override
    public void show() {
        super.show();
        System.out.println("穿上长袖");
    }
}

牛仔裤

public class Jeans extends Cloth {

    public Jeans(People people) {
        super(people);
    }

    @Override
    public void show() {
        super.show();
        System.out.println("穿上牛仔裤");
    }

}

鞋子

public class Shoe extends Cloth {

    public Shoe(People people) {
        super(people);
    }

    @Override
    public void show() {
        super.show();
        System.out.println("穿上鞋子");
    }

}

使用

public static void main(String[] args) {

        People people = new People("mi");
        Sleeves sleeves = new Sleeves(people);
        Jeans jeans = new Jeans(sleeves);
        Shoe shoe = new Shoe(jeans);

        shoe.show();
    }

打印

装扮人是:mi
穿上长袖
穿上牛仔裤
穿上鞋子

相关文章

网友评论

      本文标题:装饰模式

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