【发布时间】:2016-02-16 19:21:05
【问题描述】:
受Decorator 模式的启发,但确信该模式的要点可以以较低的复杂性实现,我制作了两个快速的 sn-ps,分别用 C++11 和 Java 编写。
装饰器.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;
}
装饰器.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。
那么,这些被剥离的“装饰器”有哪些实际缺点?
【问题讨论】: