原博主地址:(https://blog.csdn.net/LoveLion/article/details/17517213)
装饰模式和桥接模式的区别是,桥接模式一次只能使用一个桥接,笔沾了颜料之后,要想再沾其他颜料,需要把之前的颜料洗掉,而装饰不一样,装饰了颜色框之后,还可以在装饰花纹框。
装饰模式(Decorator Pattern):动态地给一个对象增加一些额外的职责,就增加对象功能来说,装饰模式比生成子类实现更为灵活。装饰模式是一种对象结构型模式。
装饰接口
package test2019.mon01.装饰模式;
/**
* Filename: Component.java
* Description:
* Company: sendinfo.com.cn Inc.
* @author: guzhangyan
* @date: 2019年1月28日 上午10:59:35
*/
public interface Component {
public void display();
}
窗户类
package test2019.mon01.装饰模式;
/**
* Filename: Window.java
* Description:
* Company: sendinfo.com.cn Inc.
* @author: guzhangyan
* @date: 2019年1月28日 上午11:00:15
*/
public class Window implements Component{
@Override
public void display() {
System.out.println("装饰窗户");
}
}
门类
package test2019.mon01.装饰模式;
/**
* Filename: Door.java
* Description:
* Company: sendinfo.com.cn Inc.
* @author: guzhangyan
* @date: 2019年1月28日 上午11:01:28
*/
public class Door implements Component {
@Override
public void display() {
System.out.println("装饰门");
}
}
装饰抽象类
package test2019.mon01.装饰模式;
/**
* Filename: ComponentDecorator.java
* Description:
* Company: sendinfo.com.cn Inc.
* @author: guzhangyan
* @date: 2019年1月28日 上午11:02:18
*/
public abstract class ComponentDecorator implements Component{
private Component component;
public ComponentDecorator(Component component) {
this.component = component;
}
@Override
public void display() {
component.display();
}
}
黑色框装饰类
package test2019.mon01.装饰模式;
/**
* Filename: BlackDecorator.java
* Description:
* Company: sendinfo.com.cn Inc.
* @author: guzhangyan
* @date: 2019年1月28日 上午11:05:16
*/
public class BlackDecorator extends ComponentDecorator {
public BlackDecorator(Component component) {
super(component);
}
@Override
public void display() {
this.showDisPlay();
super.display();
}
private void showDisPlay() {
System.out.println("展示黑色框");
}
}
花式装饰类
package test2019.mon01.装饰模式;
/**
* Filename: BlackDecorator.java
* Description:
* Company: sendinfo.com.cn Inc.
* @author: guzhangyan
* @date: 2019年1月28日 上午11:05:16
*/
public class FlowerDecorator extends ComponentDecorator {
public FlowerDecorator(Component component) {
super(component);
}
@Override
public void display() {
this.showDisPlay();
super.display();
}
private void showDisPlay() {
System.out.println("展示花式框");
}
}
测试类
package test2019.mon01.装饰模式;
/**
* Filename: Test.java
* Description:
* Company: sendinfo.com.cn Inc.
* @author: guzhangyan
* @date: 2019年1月28日 上午11:16:39
*/
public class Test {
public static void main(String[] args) {
Window window = new Window();
BlackDecorator blackDecorator = new BlackDecorator(window);
FlowerDecorator flowerDecorator = new FlowerDecorator(blackDecorator);
blackDecorator = new BlackDecorator(flowerDecorator);
blackDecorator.display();
}
}
测试结果
展示黑色框
展示花式框
展示黑色框
装饰窗户