`
xgcai
  • 浏览: 8188 次
  • 性别: Icon_minigender_1
  • 来自: 惠州
社区版块
存档分类
最新评论

设计模式-装饰模式

 
阅读更多

装饰模式(包装器):动态地为对象添加一些额外的职责。

 

装饰模式是动态地扩展一个对象的功能,而不需要改变原始类代码。

 

装饰模式主要包括四种角色:

1、抽象组件(Component):定义了“被装饰者”需要进行装饰的方法。

2、具体组件(ConcreteComponent):抽象组件的子类,具体组件实例也称为“被装饰者”

3、装饰(Decorator):也是抽象组件的子类,还包含了抽象子组件变量,该类的实例称为“装饰者”。

4、具体装饰者(ConcreteDecorator):是装饰者的一个非抽象子类,该类的实例称为“装饰者”。

 

装饰者的类图:



 

 

 

 

 

例子说明:

现有一只麻雀能够飞行100M,假如想让麻雀能够飞行到150M,又不修改麻雀类代码,通过给麻雀安装一对电子翅膀,让麻雀能够飞行所要求的距离。

 

/**
 * 
 */
package org.rico.pattern.demo.decorator;

/**
 * @author rico 2013-3-10
 * 抽象组件
 */
public abstract class Bird {
	public abstract int fly();
}

 

/**
 * 
 */
package org.rico.pattern.demo.decorator;

/**
 * @author rico 2013-3-10
 * 具体组件
 */
public class Sparrow extends Bird {
	public static final int DISTANCE = 100;

	public Sparrow() {}
	
	/* (non-Javadoc)
	 * @see org.rico.pattern.demo.decorator.Bird#fly()
	 */
	@Override
	public int fly() {
		return DISTANCE;
	}

}

 

/**
 * 
 */
package org.rico.pattern.demo.decorator;

/**
 * @author rico 2013-3-10
 * 装饰器
 */
public abstract class Decorator extends Bird {
	protected Bird bird;
	
	public Decorator() {}
	
	public Decorator(Bird bird) {
		this.bird = bird;
	}
}

 

/**
 * 
 */
package org.rico.pattern.demo.decorator;

/**
 * @author rico 2013-3-10
 * 具体装饰器
 */
public class SparrowDecorator extends Decorator {
	public static final int DISTANCE = 50;
	
	public SparrowDecorator(Bird bird) {
		super(bird);
	}

	/* (non-Javadoc)
	 * @see org.rico.pattern.demo.decorator.Bird#fly()
	 */
	@Override
	public int fly() {
		return bird.fly()+extFly();		//开挂,让麻雀能多50
	}
	
	//装饰器新增方法
	private int extFly() {
		return DISTANCE;
	}

}

 

/**
 * 
 */
package org.rico.pattern.demo.decorator;

/**
 * @author rico 2013-3-10
 * 
 */
public class test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Bird bird = new Sparrow();								//能飞100米的麻雀
		Decorator decoratorOne = new SparrowDecorator(bird);	//能飞150米的麻雀
		Decorator decoratorTwo = new SparrowDecorator(decoratorOne);//能飞200米的麻雀
		
		System.out.println("######################################");
		System.out.println("####decoratorOne: " + decoratorOne.fly() + "####decoratorTwo: " + decoratorTwo.fly());
		System.out.println("######################################");
	}

}

 

 

 

 

 

 

 

 

 

 

 

  • 大小: 20.7 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics