Java中有许多设计模式,本片文章通过一个简化的装饰模式的代码,实现一个简单的装饰模式。
package com.java;
public interface Component
{
public void doSomething();
}
package com.java;
public class ConcreteComponent implements Component
{
@Override
public void doSomething()
{
System.out.println("funcation A");
}
}
package com.java;
public class Decorator implements Component
{
private Component component;
public Decorator(Component component)
{
this.component = component;
}
@Override
public void doSomething()
{
component.doSomething();
}
}
package com.java;
public class ConcreteDecorator extends Decorator
{
public ConcreteDecorator(Component component)
{
super(component);
}
@Override
public void doSomething()
{
super.doSomething();
this.doAnotherThing();
}
public void doAnotherThing()
{
System.out.println("funcation B");
}
}
package com.java;
public class ConcreteDecorator1 extends Decorator
{
public ConcreteDecorator1(Component component)
{
super(component);
}
@Override
public void doSomething()
{
super.doSomething();
this.doAnotherThing();
}
public void doAnotherThing()
{
System.out.println("funcation C");
}
}
package com.java;
public class Client
{
public static void main(String[] args)
{
Component con = new ConcreteComponent();
Component con1 = new ConcreteDecorator(con);
Component con2 = new ConcreteDecorator1(con1);
con2.doSomething();
}
}
运行结果如下
funcation A
funcation B
funcation C