装饰模式,利用了setComponent来对对象进行包装。
class Person {
private String name;
public Person(){}
public Person(String name){
this.name = name;
}
public void show() {
System.out.println("装扮的" + name);
}
}
// 装饰类
class Decorator extends Person{
protected Person person;
public void setComponent(Person person){
this.person = person;
}
public void show(){
if(person != null)
person.show();
}
}
// 不同的装饰
class Tshirts extends Decorator{
public void show(){
System.out.print("T恤 ");
super.show();
}
}
class BigTrouser extends Decorator{
public void show(){
System.out.print("垮裤 ");
super.show();
}
}
class Sneakers extends Decorator{
public void show(){
System.out.print("破球鞋 ");
super.show();
}
}
class LeatherShoes extends Decorator{
public void show(){
System.out.print("皮鞋 ");
super.show();
}
}
class Suit extends Decorator{
public void show(){
System.out.print("西装 ");
super.show();
}
}
class Tie extends Decorator{
public void show(){
System.out.print("领带 ");
super.show();
}
}
public class Test{
public static void main(String[] args){
Person person = new Person("kingc");
System.out.println("第一种装扮");
Sneakers sk = new Sneakers();
BigTrouser bt = new BigTrouser();
Tshirts ts = new Tshirts();
sk.setComponent(person);
bt.setComponent(sk);
ts.setComponent(bt);
ts.show();
System.out.println("第二种装扮");
LeatherShoes ls = new LeatherShoes();
Tie tie = new Tie();
Suit suit = new Suit();
ls.setComponent(person);
tie.setComponent(ls);
suit.setComponent(tie);
suit.show();
}
}
输出:
第一种装扮
T恤 垮裤 破球鞋 装扮的kingc
第二种装扮
西装 领带 皮鞋 装扮的kingc
分享到:
相关推荐
装饰模式是Erich Gamma等人所著的《设计模式:可利用面向对象软件的基础》一书中众多模式之一。一般来说,此模式在设计Swing的程序员中比较流行,他们用它来改进软件。今天,即使有许多程序是基于Web应用的,装饰...
java设计模式之装饰模式java设计模式之装饰模式java设计模式之装饰模式java设计模式之装饰模式java设计模式之装饰模式java设计模式之装饰模式java设计模式之装饰模式java设计模式之装饰模式
设计模式 c# 装饰模式
装饰模式.doc 装饰模式.doc 装饰模式.doc
C++23种设计模式之 装饰模式。:当你向旧的类中添加新代码时,一般是为了添加核心职责或主要行为。而当需 要加入的仅仅是一些特定情况下才会执行的特定的功能时(简单点就是不是核心应用的功 能),就会增加类的...
装饰模式的一个简单实例,小猪吃苹果的游戏,每吃一种苹果,增加一种不同的功能。装饰模式是在不必改变原类文件和使用继承的情况下,动态的扩展一个对象的功能。
JAVA设计模式之装饰模式代码
装饰模式: 装饰模式是为已有功能动态的添加更多功能的一种方法。 如果需要为一个主类里添加新的字段,新的方法和新的逻辑,而这些新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为, 那么就...
设计模式 - 装饰模式(C++实例) 若有问题,请指出。
软件设计模式之装饰模式讲解ppt,可用于教学课件。
设计模式C++学习之装饰模式(Decorator)
装饰模式的示例代码和文档,学习装饰模式的参考资料。
根据售卖咖啡的过程,客户先选择一种口味的咖啡,又选择不同种类的配料,由于配料选择是不定的,符合装饰模式的应用情况。
23种设计模式--装饰模式
装饰模式简单例子,根据《Head First设计模式》第3章中的咖啡店的例子编写
Java的装饰模式的实例代码,生成密码的实例
实验九:装饰模式.rar实验九:装饰模式.rar中有小猪游戏,肖像画加装饰物以及咖啡茶的装饰
通过设计组装和升级大众CC来说明装饰模式,有一个VolkCC类实现Volk接口,设计一个CCDecorator实现Volk这个接口,在ConcreteCCDecorator这个具体装饰角色中进行功能的增加和重写。
装饰模式(Decorator),动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
C#设计模式之Decorator 装饰模式,pdf+视频教学,实例演示,易学易用~~