interface Component {
/**原始接口*/
public void go();
}
//2. 具体构件
class ConcreteComponent implements Component {
public void go() {
System.out.println("行走");
}
}
//.装饰角色来了
class Decorator implements Component {
/**持有私有的原始构件*/
private Component component;
/**构造子,委派给原始构件*/
protected Decorator(Component component) {
this.component = component;
}
/**调用原始构件功能,通常就可直接把扩展功能加在此方法中*/
public void go() {
this.component.go();
}
}
//具体装饰(这里演示了两种扩展的情况,走路+听音乐和唱歌s)
class ConcreteDecoratorListen extends Decorator {
/**构造子,相关初始化*/
public ConcreteDecoratorListen(Component component) {
super(component);
// code is here
}
/**商业逻辑,对原始构件功能的扩展*/
public void go() {
listen("听音乐");//执行扩展功能
super.go();
}
private void listen(Object obj){
System.out.println(obj);
}
}
class ConcreteDecoratorSing extends Decorator {
/**构造子,相关初始化*/
public ConcreteDecoratorSing(Component component) {
super(component);
// code is here
}
/**商业逻辑,对原始构件功能的扩展*/
public void go() {
super.go();
System.out.println(sing());;// 执行扩展功能
}
private String sing() {
return"唱歌";
}
}
//客户端调用
public class testDecorate {
public static void main(String[] args) {
/**原始构件*/
Component component = new ConcreteComponent();
/**边听音乐,边走路*/
ConcreteDecoratorListen cdl = new ConcreteDecoratorListen(component);
cdl.go();
System.out.println();
/**边走路,边唱歌*/
ConcreteDecoratorSing cds = new ConcreteDecoratorSing(component);
cds.go();
System.out.println();
//走路,唱歌,听音乐
ConcreteDecoratorListen cdl2 = new ConcreteDecoratorListen(component);
ConcreteDecoratorSing cds2 = new ConcreteDecoratorSing(cdl2);
cds2.go();
}
}
- 大小: 39.8 KB
- 大小: 54.5 KB
分享到:
相关推荐
设计模式专题之(七)装饰模式---设计模式装饰模式示例代码(python--c++)
C++23种设计模式之 装饰模式。:当你向旧的类中添加新代码时,一般是为了添加核心职责或主要行为。而当需 要加入的仅仅是一些特定情况下才会执行的特定的功能时(简单点就是不是核心应用的功 能),就会增加类的...
iOS 设计模式 装饰模式
软件设计模式之装饰模式讲解ppt,可用于教学课件。
C#设计模式 装饰模式源码 component ConcreteDecorator
Java 经典设计模式讲解以及项目实战 设计模式简介:主要介绍各种设计模式的概念和运用场景等 设计模式综合运用:主要是笔者在实际工作中运用到的一些设计模式综合运用事例的提炼 Spring设计模式简介:主要是讲述...
设计模式 - 装饰模式(C++实例) 若有问题,请指出。
设计模式--装饰者模式java例子
设计模式装饰模式PPT学习教案.pptx
HeadFirst 设计模式学习笔记3--装饰模式 Demo http://blog.csdn.net/laszloyu/archive/2010/05/12/5582561.aspx
java设计模式之装饰者模式代码
设计模式07-组合模式、装饰模式 设计模式09-外观模式、享元模式 设计模式10-代理模式、结构型模式大复习 设计模式11-行为模式-责任链、命令模式 设计模式12-解释器模式 设计模式13-迭代器模式 设计模式14-中介者模式...
设计模式主要分为三大类: 1.创建型模式:工厂模式、抽象工厂模式、单例模式、建造者模式、原型模式。 2.结构型模式:适配器模式、桥接模式、装饰模式、组合模式、外观模式、享元模式、代理模式。 4.行为型模式:...
23个设计模式之一的装饰模式,java编写的代码示例,极客学院课程的设计模式下载的课件资料,附上Head First设计模式第三版的pdf,另外还有UML基础,案例与应用的pdf
设计模式 c# 装饰模式
总体来说设计模式分为三大类: 创建型模式,共五种:工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。 结构型模式,共七种:适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元...
设计模式相关资料设计模式相关资料设计模式相关资料设计模式相关资料设计模式相关资料设计模式相关资料
该系统是一个画图程序,我们要用设计模式的思想来设计系统结构,然后实现基本图形的绘制功能。 1.1 设计模式要求 在软件的设计中请使用到三种以上设计模式。 1.2 画图基本要求 能实现基本图形的绘制功能,包括实现...
JAVA设计模式之装饰模式代码
软件设计模式作业,要求用3个设计模式以上实现。代码涉及了装饰模式,工厂模式和适配器模式