美文网首页
装饰模式(Dcorator)

装饰模式(Dcorator)

作者: bobcorbett | 来源:发表于2017-08-16 09:59 被阅读0次

装饰模式(Dcorator),动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

主函数

public class main {
    public static void main(String[] args) {
        Person xc = new Person("小菜");

        System.out.println("\n第一种装扮");

        Sneakers pqx = new Sneakers();
        BigTrouser kk = new BigTrouser();
        TShirts dtx = new TShirts();

        pqx.Decorate(xc);
        kk.Decorate(pqx);
        dtx.Decorate(kk);
        dtx.Show();

        System.out.println("\n第二种装扮");

        LeatherShoes px = new LeatherShoes();
        Tie ld = new Tie();
        Suit xz = new Suit();

        px.Decorate(xc);
        ld.Decorate(px);
        xz.Decorate(ld);
        xz.Show();
    }
}

装饰器父类(顶级类)

public class Person {
    public Person() {

    }
    private String name;
    public Person(String name) {
        this.name = name;
    }

    public void Show() {
        System.out.println("装扮的{"+name+"}");
    }
}

子类

public class Finery extends Person {
    protected Person component;

    public void Decorate(Person component) {
        this.component = component;
    }

    @Override
    public void Show() {
        if(component != null)
            this.component.Show();
    }
}

孙子类

public class Sneakers extends Finery {
    public void Show() {
        System.out.print("破球鞋 ");
        super.Show();
    }
}
public class BigTrouser extends Finery {
    public void Show() {
        System.out.print("垮裤 ");
        super.Show();
    }
}
public class Suit extends Finery {
    public void Show() {
        System.out.print("西装 ");
        super.Show();
    }
}
public class Tie extends Finery {
    public void Show() {
        System.out.print("领带 ");
        super.Show();
    }
}
public class TShirts extends Finery {
    public void Show() {
        System.out.print("大T恤 ");
        super.Show();
    }
}
public class LeatherShoes extends Finery {
    public void Show() {
        System.out.print("皮鞋 ");
        super.Show();
    }
}

相关文章

  • 装饰模式(Dcorator)

    装饰模式(Dcorator),动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。 主...

  • 装饰者(Decorator)模式

    装饰者(Decorator)模式装饰模式又名包装(Wrapper)模式。装饰模式是继承关系的一个替代方案。装饰模式...

  • 11.4设计模式-装饰模式-讲解

    设计模式-装饰模式 装饰模式详解 装饰模式在android中的实际运用,避免了耦合 1. 装饰模式详解 2.装饰模...

  • 如何利用装饰者模式在不改变原有对象的基础上扩展功能

    目录 什么是装饰者模式 普通示例 装饰者模式示例 类图关系 装饰者模式使用场景 装饰者模式优点 装饰者模式缺点 什...

  • 第4章 结构型模式-装饰模式

    一、装饰模式简介 二、装饰模式的优缺点 三、装饰模式的使用场景 四、装饰模式的实例

  • 让你再也忘不了IO相关知识-Java IO图文详解

    1 装饰模式 Java中IO使用的是装饰模式,装饰模式在Android中很常见,比如系统的Context。 装饰模...

  • 装饰者模式

    在《JAVA与模式》一书开头是这样描述装饰(Decorator)模式的: 装饰模式又名包装模式。装饰模式以对客户端...

  • 设计模式之装饰器模式

    在阎宏博士的《JAVA与模式》的书中,对装饰器模式的描述如下:装饰模式又名包装(Wrapper)模式。装饰模式以对...

  • 装饰者模式

    装饰者模式 装饰者模式和适配器模式对比 装饰者模式 是一种特别的适配器模式 装饰者与被装饰者都要实现同一个接口,主...

  • iOS开发之设计模式 - 装饰模式

    由《大话设计模式 - 装饰模式》的OC和部分Swift的语言转义 装饰模式 继上一篇《策略模式》 装饰模式,动态地...

网友评论

      本文标题:装饰模式(Dcorator)

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