2016-02-16 27 views
0

Decorator模式的启发,但确定该模式的要点可以以较低的复杂度实现,我分别在C++ 11和Java中创建了两个快速片段。原始装饰器的实际缺点

Decorator.cpp:

#include <iostream> 
#include <string> 

using namespace std; 

class Box { 

public: 
    virtual string getDescription() 
    { 
     return "A box"; 
    } 
}; 

class BoxDecorator : public Box { 
    Box* wrapee; 

public: 
    BoxDecorator(Box* box) 
    { 
     wrapee = box; 
    } 
    string getDescription() 
    { 
     return wrapee->getDescription(); 
    } 
}; 

class RedBox : public BoxDecorator { 

public: 
    RedBox(Box* box) 
     : BoxDecorator(box) 
    { 
    } 

    string getDescription() 
    { 
     return BoxDecorator::getDescription() + ", red-colored"; 
    } 
}; 

class BigBox : public BoxDecorator { 

public: 
    BigBox(Box* box) 
     : BoxDecorator(box) 
    { 
    } 

    string getDescription() 
    { 
     return BoxDecorator::getDescription() + ", big-sized"; 
    } 
}; 

class StripedBox : public BoxDecorator { 

public: 
    StripedBox(Box* box) 
     : BoxDecorator(box) 
    { 
    } 

    string getDescription() 
    { 
     return BoxDecorator::getDescription() + ", with several stripes around it"; 
    } 
}; 

int main() 
{ 
    Box* sampleBox = new StripedBox(new RedBox(new BigBox(new Box()))); 
    cout << sampleBox->getDescription() << endl; 
} 

Decorator.java:

class Box { 

public Box() { 

} 

public String getDescription() { 
    return "A box"; 
} 

} 

class BoxDecorator extends Box { 

Box boxToBeDecorated; 

public BoxDecorator(Box box) { 
    boxToBeDecorated = box; 
} 

public String getDescription() { 
    return boxToBeDecorated.getDescription(); 
} 


} 

class RedBox extends BoxDecorator { 

public RedBox(Box box) { 
    super(box); 
} 

public String getDescription() { 
    return super.getDescription() + ", red-colored"; 
} 
} 

class BigBox extends BoxDecorator { 

public BigBox(Box box) { 
    super(box); 
} 

public String getDescription() { 
    return super.getDescription() + ", big-sized"; 
} 
} 

class StripedBox extends BoxDecorator { 

public StripedBox(Box box) { 
    super(box); 
} 

public String getDescription() { 
    return super.getDescription() + ", with several stripes around it"; 
} 
} 

public class Decorator { 

public static void main(String[] args) { 

    Box sampleBox = new StripedBox(new RedBox(new BigBox(new Box()))); 
    System.out.println(sampleBox.getDescription()); 

} 
} 

两者都产生有效的 “一箱,大尺寸,红色,与周围的若干个磁条” 的输出。因此,例如,在Java的情况下,语言的复杂性并不会影响我们to use interfaces or abstract classes

那么,这些剥离的“装饰者”的实际弊端?

回答

1

这里您继承Box的实现。这需要记忆,可能会导致问题(例如构造函数可能有副作用)。没有继承Box的理由。另外,如果使用继承,修饰符链的可能组合的数量将呈指数增长。

+0

有点好奇,从盒子继承Decorator时如何影响内存。我想象一下Box的内存很大,然后装饰器实例会在内部膨胀,这对性能来说是非常糟糕的。这或多或少接近你的观点? – fyodorananiev

+1

是的,你是对的。即使明显不被使用,超类的所有成员字段都会占用内存。 – dzidzitop