欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

java设计模式学习之装饰模式

时间:2021-04-07 10:12:16|栏目: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 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恤
垮裤
破球鞋
装扮的旺财

上一篇:如何通过Kaptcha在Web页面生成验证码

栏    目:JAVA代码

下一篇:Java 8中如何获取参数名称的方法示例

本文标题:java设计模式学习之装饰模式

本文地址:http://www.codeinn.net/misctech/96267.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有