java常用设计模式(装饰者模式)
2017-10-23 21:50
549 查看
一:装饰者设计模式(Decorator),先上代码.
抽象的组件(AbstractComponent)
抽象装饰者(Abstract[b]Component)[/b]
下面继续
具体装饰者(ConcreteDecorator)
具体装饰者(ConcreteDecorator)
继续测试
由上面的代码可以看看是层层包装的,A包装了animal,B包装了A,都是调用eat方法,实现不同的功能拓展.
可以有无数个组件层层包装.
抽象的组件(AbstractComponent)
public interface Animal { void eat(); }具体的组件(ConcreteComponent)
public class Dog implements Animal { @Override public void eat() { System.out.println("我是狗的eat(),我在吃牛肉干"); } }
抽象装饰者(Abstract[b]Component)[/b]
public abstract class Decorator implements Animal { protected Animal animal; public void setAnimal(Animal animal) { this.animal = animal; } @Override public void eat() { System.out.println("我是装饰者实现的eat(),请开始下面的表演"); animal.eat(); } }测试
public class Test { public static void main(String[] args) { Animal animal = new Dog(); Decorator decorator = new Decorator(); decorator.setAnimal(animal); decorator.eat(); } } //执行结果:(增加了装饰者的逻辑) 我是装饰者实现的eat(),请下开始下面的表演 我是狗的eat(),我在吃牛肉干
下面继续
具体装饰者(ConcreteDecorator)
public class DogDecoratorA extends Decorator { public void eat(){ super.eat(); System.out.println("我是DogDecoratorA"); eatOther(); } public void eatOther() { System.out.println("牛肉干不好吃,我要吃石头"); } }继续测试
public class Test2 { public static void main(String[] args) { Animal animal = new Dog(); Decorator decorator = new DogDecoratorA(); decorator.setAnimal(animal); decorator.eat(); } } //执行结果(dogA的装饰) 我是装饰者实现的eat(),请下开始下面的表演 我是狗的eat(),我在吃牛肉干 我是DogDecoratorA 牛肉干不好吃,我要吃石头
具体装饰者(ConcreteDecorator)
public class DogDecoratorB extends Decorator { public void eat(){ super.eat(); System.out.println("我是DogDecoratorB,我听你的吃了石头,来你过来一下"); } }
继续测试
public class Test3 { public static void main(String[] args) { Animal animal = new Dog(); Decorator decoratorA = new DogDecoratorA(); Decorator decoratorB = new DogDecoratorB(); decoratorA.setAnimal(animal); decoratorB.setAnimal(decoratorA); decoratorB.eat(); } } //执行结果 我是装饰者实现的eat(),请下开始下面的表演 我是装饰者实现的eat(),请下开始下面的表演 我是狗的eat(),我在吃牛肉干 我是DogDecoratorA 牛肉干不好吃,我要吃石头 我是DogDecoratorB,我听你的吃了石头,来你过来一下总结:装饰模式和继承的主要区别是:装饰模式是针对对象的,而继承是针对类的。
由上面的代码可以看看是层层包装的,A包装了animal,B包装了A,都是调用eat方法,实现不同的功能拓展.
可以有无数个组件层层包装.
相关文章推荐
- Java常用GoF设计模式之一装饰者模式
- Java中常用设计模式总结
- Java常用的设计模式
- java常用的设计模式
- Java常用设计模式
- java 23种设计模式中常用的九种
- java常用的设计模式
- java软件体系结构设计模式----装饰者
- Java常用的设计模式
- [转]Java中常用设计模式总结
- java 23种设计模式中常用的九种
- java开发中C/S的一种常用设计模式(学习中)
- Java 装饰者设计模式
- java常用设计模式
- Java常用的设计模式
- Java常用的设计模式
- Java23种常用设计模式
- java常用设计模式
- java常用类库续3(比较器Comparable、Comparator、观察者设计模式、正则表达式、定时调度)
- Java中常用设计模式总结