Java装饰器设计模式初探
程序员文章站
2022-04-25 10:23:49
...
本篇随笔主要介绍用Java实现简单的装饰器设计模式:
先来看一下装饰器设计模式的类图:
从图中可以看到,我们可以装饰Component接口的任何实现类,而这些实现类也包括了装饰器本身,装饰器本身也可以再被装饰。
下面是用Java实现的简单的装饰器设计模式,提供的是从基本的加入咖啡入手,可以继续加入牛奶,巧克力,糖的装饰器系统。
interface Component { void method(); } class Coffee implements Component { @Override public void method() { // TODO Auto-generated method stub System.out.println("倒入咖啡"); } } class Decorator implements Component { public Component comp; public Decorator(Component comp) { this.comp = comp; } @Override public void method() { // TODO Auto-generated method stub comp.method(); } } class ConcreteDecorateA extends Decorator { public Component comp; public ConcreteDecorateA(Component comp) { super(comp); this.comp = comp; } public void method1() { System.out.println("倒入牛奶"); } public void method2() { System.out.println("加入糖 "); } public void method() { super.method(); method1(); method2(); } } class ConcreteDecorateB extends Decorator { public Component comp; public ConcreteDecorateB(Component comp) { super(comp); this.comp = comp; } public void method1() { System.out.println("加入巧克力"); } public void method() { super.method(); method1(); } } public class TestDecoratePattern { public static void main(String[] args) { Component comp = new Coffee(); comp.method(); System.out.println("--------------------------------------------------"); Component comp1 = new ConcreteDecorateA(comp); comp1.method(); System.out.println("--------------------------------------------------"); Component comp2 = new ConcreteDecorateB(comp1); comp2.method(); System.out.println("--------------------------------------------------"); Component comp3 = new ConcreteDecorateB(new ConcreteDecorateA(new Coffee())); comp3.method(); System.out.println("--------------------------------------------------"); Component comp4 = new ConcreteDecorateA(new ConcreteDecorateB(new Coffee())); comp4.method(); } }
运行结果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。
更多Java装饰器设计模式初探相关文章请关注PHP中文网!