• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Java之装饰模式学习

java 搞代码 4年前 (2022-01-09) 11次浏览 已收录 0个评论

这篇文章主要为大家详细介绍了java设计模式学习之装饰模式的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

优点:装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。

缺点:多层装饰比较复杂。

实例:给一个人配置穿衣

1:代码结构图

2:创建一个person类( ConcreteComponent)

package DecoratorModel;/** * 2017-10-9 10:39:09 * 装饰器设计模式 * Person 类 ConcreteComponent * @author 我不是张英俊 * */public class Person {  public Person(){}    private String name;  public Person(String name){    this.name=name;  }    public void Show(){    System.out.println("装扮的"+name);  }}

3:服饰类

package DecoratorModel;/** *服饰类(Decorator) * @author 我不是张英俊 * */public class Finery extends Person{  protected Person component;  //打扮  public void Decorate(Person component){    this.component=component;  }    public void Show(){    if(component!=null){      component.Show();    }  }}

4:具体服饰类

public class Tshirts extends Finery {  public void Show(){    System.out.println("大T恤");    super.Show();    }}public class BigTrouser extends Finery {  public void Show(){    System.out.println("垮裤");    super.Show();  }}public class Sneakers extends Finery {  public void Show(){    System.out.println("破球鞋");    super.Show();    }}public class Suit extends Finery {  public void Show(){    System.out.println("西装");    super.Show();  }}public class <strong style="color:transparent">本文来源gao@daima#com搞(%代@#码@网&</strong>Tie extends Finery {  public void Show(){    System.out.println("领带");    super.Show();  }}public class LeatherShoes extends Finery {  public void Show(){    System.out.println("皮鞋");    super.Show();  }}

5:测试类

public class test {  public static void main(String[] args) {    Person xc=new Person("旺财");        Sneakers pqx=new Sneakers();    BigTrouser kk=new BigTrouser();    Tshirts dtx=new Tshirts();    pqx.Decorate(xc);    kk.Decorate(pqx);    dtx.Decorate(kk);    dtx.Show();  }}

6:控制台

大T恤
垮裤
破球鞋
装扮的旺财

以上就是Java之装饰模式学习的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Java之装饰模式学习

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址