装饰模式-Decorator Pattern

基本概念

装饰模式,动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比使用子类继承父类更为灵活,装饰模式可以有效地把类的核心职责和附加功能区分开。

结构图

 

上图摘自《大话设计模式》

应用场景

当需要往旧的类中添加新的方法或新的逻辑的时候,如果在主类中添加,会增加主类的复杂度;这些需要加入的东西如果仅仅是为了满足某些特定行为的需要,可以作为装饰功能来添加,从而使用装饰模式,使主类不变,仅负责核心职责的实现。

源码示例(以绘制图形作为主类核心职责,以添加边框颜色作为装饰功能)

1.创建Shape接口

package com.spook.decorator;

/**
 * Shape接口
 */
public interface Shape {
	public void draw();

}
2.创建Circle类

package com.spook.decorator;

/**
 * Circle类
 */
public class Circle implements Shape {

	@Override
	public void draw() {
		// TODO Auto-generated method stub
		System.out.println("draw circle");
	}

}
3.创建Square类

package com.spook.decorator;

/**
 * Square类
 */
public class Square implements Shape {

	@Override
	public void draw() {
		// TODO Auto-generated method stub
		System.out.println("draw square");
	}

}
4.装饰者抽象类,实现Shape接口

package com.spook.decorator;

/**
 * 装饰者抽象类
 */
public abstract class ShapeDecorator implements Shape {

	protected Shape decoratedShape;

	public ShapeDecorator(Shape shape) {
		this.decoratedShape = shape;
	}

	@Override
	public void draw() {
		// TODO Auto-generated method stub
		if (decoratedShape != null) {
			decoratedShape.draw();
		}
	}

}
5.蓝色边框装饰功能实现类

package com.spook.decorator;

/**
 * 蓝色边框装饰者类
 */
public class BlueShapeDecorator extends ShapeDecorator {

	public BlueShapeDecorator(Shape shape) {
		super(shape);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void draw() {
		// TODO Auto-generated method stub
		super.draw();
		setBlueBorder(decoratedShape);
	}

	private void setBlueBorder(Shape decoratedShape) {
		System.out.println("Border Color: Blue");
	}

}
6.红色边框装饰功能实现类

package com.spook.decorator;

/**
 * 红色边框装饰者类
 */
public class RedShapeDecorator extends ShapeDecorator {

	public RedShapeDecorator(Shape shape) {
		super(shape);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void draw() {
		// TODO Auto-generated method stub
		super.draw();
		setRedBorder(decoratedShape);
	}
	
	private void setRedBorder(Shape decoratedShape) {
		System.out.println("Border Color: Red");
	}
}
7.测试类
package com.spook.decorator;

/**
 * 测试类
 */
public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Shape blueCircle = new BlueShapeDecorator(new Circle());
		blueCircle.draw();

		Shape redSquare = new RedShapeDecorator(new Square());
		redSquare.draw();

	}

}
运行测试类输出如下内容:

draw circle
Border Color: Blue
draw square
Border Color: Red

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值