装饰模式:动态地给一个对象添加一些额外的职责,就增加功能而言,装饰者模式比生成子类更加灵活。Component是定义一个对象接口,可以给这些对象动态地添加职责,ConcreteComppnent是定义了一个具体的对象,也可以给这个对象添加一些职责,Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的,至于ConcreteDecorator就是具体的装饰对象,起到给Component添加职责的功能
上面是装饰者模式Decorator的类图。
实现代码如下:
Component类:
abstract class Component{
public abstract void operation();
}
ConcreteComponent类:
class ConcreteCompoent extends Component{
public void operation{
System.out.println("具体对象的操作:");
}
}
Decorator类:
abstract class Decorator extends Compoent{
protected Component compoent;
pbulic void setComponent(Component component){
this.component = component;
}
public void operation(){
if(component!=null){
component.Operation();
}
}
}
class ConcreteDecortorA extends Decorator{
private String addedState;
public void operation(){
super.operation();
addedState = "new Stare";
System.out.println("具体装饰对象A的操作");
}
}
class ConcreteDecortorB extends Decorator{
public void Operation(){
super.Operation();
AddedBehavior();
System.out.println("具体装饰对象B的操作");
}
private void AddedBehavior(){
}
}
public class Test{
public static void main(String[] args) {
ConcreteComponent c = new ConcreteComponent();
ConcreteComponentA d1 = new ConcreteComponentA();
ConcreteComponentB d2 = new ConcreteComponentB();
d1.setComponent(c);
d2.setComponent(d1);
d2.operation();
}
}如果只有一个ConcreteComponent类而没有抽象的Component类,那么Decotator类可以是ConcreteComponent的一个子类,同样道理,如果只有一个ConcreteDecorator类,那么就没有必要建立一个单独的Decorator类,而可以把Decorator和ConcreteDecorator的责任合并成一个类。
下面是一个例子:
public class Person {
public Person() {
}
private String name;
public Person(String name) {
this.name = name;
}
public void show() {
System.out.println("装扮的:" + name);
}
}
public class Finery extends Person {
protected Person component;
public void Decorate(Person component) {
this.component = component;
}
public void show() {
if (component != null) {
component.show();
}
}
}
class TShirts extends Finery {
public void show() {
System.out.println("大T恤");
super.show();
}
}
class BigTrouser extends Finery {
public void show() {
System.out.println("垮裤");
super.show();
}
}
class Sneakers extends Finery {
public void show() {
System.out.println("破球鞋");
super.show();
}
}
class LeatherShoes extends Finery {
public void show() {
System.out.println("皮鞋");
super.show();
}
}
class Tie extends Finery {
public void show() {
System.out.println("领带");
super.show();
}
}
class Suit extends Finery {
public void show() {
System.out.println("西装");
super.show();
}
}
public class Test {
public static void main(String[] args) {
Person xc = new Person("菜鸟");
System.out.println("第一种装扮");
Sneakers pqx = new Sneakers();
BigTrouser kk = new BigTrouser();
TShirts dtx = new TShirts();
pqx.Decorate(xc);
kk.Decorate(pqx);
dtx.Decorate(kk);
dtx.show();
}
}
原文地址:http://blog.csdn.net/chencangui/article/details/45393689