2016-02-16 50 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