设计模式——装饰器模式

1.定义

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

2.使用场景

1、扩展一个类的功能。 2、动态增加功能,动态撤销。
例如:1、孙悟空有 72 变,当他变成"庙宇"后,他的根本还是一只猴子,但是他又有了庙宇的功能。

3.实现

/**
 * 抽象组件(Component):可以是一个接口或者抽象类,充当被装饰类的原始对象,规定了被装饰对象的行为
 * @author Administrator
 *
 */
public interface Shape {
	void draw();
}
/**
 * 具体组件(ConcreteComponent):实现/继承Component的一个具体对象,即被装饰对象
 * @author Administrator
 *
 */
public class Circle implements Shape{

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

}
/**
 * 具体组件(ConcreteComponent):实现/继承Component的一个具体对象,即被装饰对象
 * @author Administrator
 *
 */
public class Rectangle implements Shape{

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

}
/**
 * 抽象装饰器(Decorator):通用的装饰ConcreteComponent的装饰器,其内部必然有一个属性指向Component,其实现一般是一个抽象类,主要为了让其子类按照其构造形式传入一个Component,
 * 这是强制的通用行为。如果系统中装饰逻辑单一,则并不需要实现许多装饰器,可以直接省略该类,而直接实现一个具体装饰器即可
 * @author Administrator
 *
 */
public class ShapeDecorator implements Shape{
	protected Shape decoratedShape;
	
	public ShapeDecorator(Shape decoratedShape) {
		// TODO Auto-generated constructor stub
		this.decoratedShape = decoratedShape;
	}

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

}
/**
 * 具体装饰器(ConcreteDecorator):Decorator的具体实现类,理论上,每个ConcreteDecorator都扩展了Component对象的一种功能
 * @author Administrator
 *
 */
public class RedShapeDecorator extends ShapeDecorator{

	public RedShapeDecorator(Shape decoratedShape) {
		super(decoratedShape);
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public void draw() {
		// TODO Auto-generated method stub
		super.draw();
		setBorderColor(decoratedShape);
	}
	
	private void setBorderColor(Shape shape) {
		System.out.println("With Red Border");
	}

}
/**
 * 测试类
 * @author Administrator
 *
 */
public class Test {
	public static void main(String[] args) {
		Shape circle = new Circle();
		circle.draw();
		
		System.out.println("=============================");
		ShapeDecorator redCircle = new RedShapeDecorator(new Circle());
		redCircle.draw();
		
		System.out.println("=============================");
		ShapeDecorator redRectangle = new RedShapeDecorator(new Rectangle());
		redRectangle.draw();
	}

}

运行结果
在这里插入图片描述

4.总结

装饰器类是对功能的增强,这也是装饰器模式应用场景的一个重要特点。

优点: 装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
缺点: 多层装饰比较复杂。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值