装饰模式----设计模式系列

简介:

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

优点:把类中的装饰功能从类中搬移去除,这样可以简化原有的类。可以有效地把类的核心职责和装饰功能区分开,而且可以去除相关类中重复的装饰逻辑。

使用场景:为已有功能动态地添加更多功能的一种方式。

下面以一个小Demo为例讲解:Tshirts(Shoe、Kuzi) extends Finery ,Finery extends Person 。Decorate为测试类

(1)被装饰的类

public class Person {

	private String name;

	public String getName() {
		return name;
	}

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

(2)装饰类

public class Finery extends Person {

	protected Person mPerson;

	public void decorate(Person person) {
		mPerson = person;
	}

	@Override
	public void show() {
		if (mPerson != null) {
			mPerson.show();
		}

	}

}

3)具体装饰类Tshirt  (Shoe和Kuzi同理)

public class TShirts extends Finery {

	@Override
	public void show() {

		System.out.println("TShirts");
		super.show();
	}
}
(4)测试类

/**装饰者模式*/
public class Decorate {

	public static void main(String[] args) {
		
		Person mPerson = new Person();
		mPerson.setName("董永康");
		
		TShirts mTShirts = new TShirts();
		Kuzi mKuzi = new Kuzi();
		Shoe mShoe = new Shoe();
		
		mTShirts.decorate(mPerson);
		mKuzi.decorate(mTShirts);
		mShoe.decorate(mKuzi);
		mShoe.show();
		
	}

}


总结 :两层继承关系, Tshirts(Shoe、Kuzi) extends Finery extends Person 。 Finery作为连接Person和Tshirts类的“桥梁”,子类show中调用super.show,在装饰的时候传递子类对象,然后调用子类对象的show方法。循环直到结束。这样做使每个装饰对象的实现和如何使用这个对象分离开了。每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当中。



相关文章
|
9月前
|
传感器 设计模式 数据库
[设计模式] --- 适配器模式
[设计模式] --- 适配器模式
62 0
|
9月前
|
设计模式
23设计模式之 --------- 什么是设计模式?
23设计模式之 --------- 什么是设计模式?
54 0
|
9月前
|
设计模式 存储
设计模式-----结构型模式
设计模式-----结构型模式
46 0
|
9月前
|
设计模式
设计模式-----创建型模式
设计模式-----创建型模式
41 0
|
9月前
|
设计模式 Java Linux
23设计模式之 ---------适配器模式
23设计模式之 ---------适配器模式
59 0
|
9月前
|
设计模式 算法 Java
23设计模式之 --------- 建造者模式
23设计模式之 --------- 建造者模式
66 0
|
9月前
|
设计模式 缓存 安全
23设计模式之 --------- 原型模式
23设计模式之 --------- 原型模式
55 0
|
9月前
|
设计模式 安全 Java
23设计模式之 ---------代理模式
23设计模式之 ---------代理模式
34 0
|
9月前
|
设计模式 网络架构
23设计模式之 --------- 工厂模式(二)
23设计模式之 --------- 工厂模式(二)
48 0
|
9月前
|
设计模式
23设计模式之 --------- 工厂模式(一)
23设计模式之 --------- 工厂模式(一)
45 0