java常用设计模式(装饰者模式)
来源:互联网 发布:vps安装python 编辑:程序博客网 时间:2024/05/19 13:24
一:装饰者设计模式(Decorator),先上代码.
抽象的组件(AbstractComponent)
public interface Animal {void eat();}具体的组件(ConcreteComponent)
public class Dog implements Animal {@Overridepublic void eat() {System.out.println("我是狗的eat(),我在吃牛肉干");}}
抽象装饰者(AbstractComponent)
public abstract class Decorator implements Animal {protected Animal animal;public void setAnimal(Animal animal) {this.animal = animal;}@Overridepublic 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方法,实现不同的功能拓展.
可以有无数个组件层层包装.
阅读全文
0 0
- java常用设计模式(装饰者模式)
- Java常用GoF设计模式之一装饰者模式
- Java设计模式-装饰者设计模式
- java设计模式---装饰者设计模式
- Java 装饰者设计模式
- Java设计模式--装饰者
- java中常用的设计模式-装饰设计模式
- Java设计模式:装饰者模式(Decorator)
- java设计模式之装饰者模式
- 【Java设计模式】装饰者模式
- Java设计模式之装饰者模式
- JAVA系列-设计模式-装饰者模式
- java设计模式之装饰者模式
- Java 设计模式 装饰者模式
- Java设计模式之装饰者模式
- Java设计模式之装饰者模式
- java设计模式------装饰者模式
- Java设计模式之装饰者模式
- java中的回调机制
- python中if __name__ == '__main__'用途说明
- maven详解-(4)修改外部资源库
- 洛谷 1313||NOIP 2011 计算系数 二项式定理 解题报告
- Linux下使用Stunnel加密Redis,实现ssl认证
- java常用设计模式(装饰者模式)
- 从1900年1月1日(星期一),开始经过的n年当中,没个月的13号这一天是星期一,星期二,星期三...星期日的次数分别是多少
- R语言入门篇
- BZOJ 4517 浅谈错位排列组合计数
- 学习正则表达式:由数字和字母组成,并且要同时含有数字和字母,且长度要在8-16位之间
- 51nod1621-贪心&枚举&好题&cf-花钱买车牌
- Adobe Premiere Pro CC 2018 Mac v12.0.0.224中文版下载
- TypeError: not all arguments converted during string formatting问题解决
- IT自学者看过来 发福利了!!! 拿走不谢