穿什么有这么重要?----装饰模式

**

穿什么有这么重要?----装饰模式

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

装饰模式结构图
“Component是定义一个对象接口,可以给这些对象动态地添加职责。ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需要知道Decorator的存在的。至于ConcreteDecorator就是具体的装饰对象,起到给Component添加职责的功能。”

//Person类(ConcreteComponent)
public class Person
{
private String name;

public Person()
{
}

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

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

}
//服饰类(Decorator)
public class Finery extends Person
{
protected Person component;

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

public void show()
{
	if (null != component)
	{
		component.show();
	}
}

}
//具体服饰类(ConcreteDecorator)
public class TShirts extends Finery
{
public void show()
{
super.show();
System.out.println(“大T恤”);
}
}
public class BigTrouser extends Finery
{
public void show()
{
super.show();
System.out.println(“大裤衩”);
}
}
public class Sneakers extends Finery
{
public void show()
{
super.show();
System.out.println(“破球鞋”);
}
}
public class Suit extends Finery
{
public void show()
{
super.show();
System.out.println(“西装”);
}
}
public class Tie extends Finery
{
public void show()
{
super.show();
System.out.println(“领带”);
}
}
public class LeatherShoes extends Finery
{
public void show()
{
super.show();
System.out.println(“皮鞋”);
}
}
//客户端代码
public class Main
{
public static void main(String[] args)
{
Person person = new Person(“小菜”);

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

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

	pqx.decorate(person);
	kk.decorate(pqx);
	dtx.decorate(kk);
	dtx.show();

	System.out.println("第二种装扮:");
	
	LeatherShoes px = new LeatherShoes();
	Tie ld = new Tie();
	Suit xz = new Suit();

	px.decorate(person);
	ld.decorate(px);
	xz.decorate(ld);
	xz.show();
}

}

结果显示:

第一种装扮:

装扮的小菜

破球鞋

大裤衩

大T恤

第二种装扮:

装扮的小菜

皮鞋

领带

西装

优点:
装饰模式提供了一个非常好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象了。而且把类中的装饰功能从类中搬移去除,这样可以简化原有的类,这样做更大的好处在于能够有效地把类的核心职责和装饰功能区分开来,而且可以去除相关类中重复的装饰逻辑。
装饰模式的装饰顺序很重要的哦,比如加密数据和过滤词汇都可以是数据持久化前的装饰功能,但若先加密了数据再用过滤功能就会出问题了,最理想的情况,是保证装饰类之间彼此独立,这样它们就可以以任意的顺序进行组合了。

猜你喜欢

转载自blog.csdn.net/weixin_42487387/article/details/89110922
今日推荐