~~结构型-装饰器模式
一:概念
装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
主要用于:原来功能不变,在原有功能上包装扩充功能
二:思路
原本的业务接口与实现类不变,重新定义一个抽象类A并继承业务口,实现接口类里的方法,接口类作为抽象类构造器的遍历,实现的接口中调用自身的业务接口。
定义抽象类A的子类B1,B2,继承A,实现抽象类里的方法,实现方法中除去调用业务接口,可以继续对写其它业务,对接口实现增强。
注:B1,B2就是原有实现类包装后的类。后面使用是可以直接使用包装后的类。
所有接口类都可以抽象出一个抽象类。
三:代码实现
package com.test.mode;
/**
* 装饰器模式
*/
public class DecoratorModeTest {
public static void main(String[] args) {
Shape2 circle = new Circle2();//正常业务
//使用实现类圆形+红色装饰==包装后的新对象
ShapeDecorator redCircle = new RedShapeDecorator(new Circle2());
//使用实现类矩形+红色装饰==包装后的新对象
ShapeDecorator redRectangle = new RedShapeDecorator(new Rectangle2());
//Shape redCircle = new RedShapeDecorator(new Circle());
//Shape redRectangle = new RedShapeDecorator(new Rectangle());
//正常调用
System.out.println("Circle with normal border");
circle.draw();
//通过装饰器调用
System.out.println("\nCircle of red border");
redCircle.draw();
//通过装饰器调用
System.out.println("\nRectangle of red border");
redRectangle.draw();
}
}
//业务接口---形状
interface Shape2 {
void draw();
}
//业务接口实现类---矩形
class Rectangle2 implements Shape2 {
@Override
public void draw() {
System.out.println("Shape: Rectangle");
}
}
//业务接口实现类---圆形
class Circle2 implements Shape2 {
@Override
public void draw() {
System.out.println("Shape: Circle");
}
}
/**
* 因为其子类都是对一个接口的增强,也就是说都是增强同一个接口类里的方法(接口类 *可能有多个实现类),所以可以对这些接口类抽象出一个抽象类。
* 而抽象类的子类都要对原来接口类的包装功能,可以选择不同实现类和对应的包装类,组合在一起就是新的包装类。
* 抽象类 定义装饰器,实现我们的业务接口
*/
abstract class ShapeDecorator implements Shape2 {
protected Shape2 decoratedShape;
public ShapeDecorator(Shape2 decoratedShape){
this.decoratedShape = decoratedShape;
}
public void draw(){
decoratedShape.draw();
}
}
/**
* 装饰器子类,具体的要对原来接口业务的扩展
* 该类是对形状装饰红色
*/
class RedShapeDecorator extends ShapeDecorator {
public RedShapeDecorator(Shape2 decoratedShape) {
super(decoratedShape);
}
@Override
public void draw() {
decoratedShape.draw();
setRedBorder(decoratedShape);
}
private void setRedBorder(Shape2 decoratedShape){
System.out.println("Border Color: Red");
}
}