开发者

Can you help me improve my decorator-based design? [closed]

开发者 https://www.devze.com 2023-01-06 05:50 出处:网络
Closed. This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this
Closed. This question needs to be more focused. It is not currently accepting answers.

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 4 years ago.

Improve this question

I have a small program to build a house. A house will have many floors (storeys), a storey can have many rooms, a room can contain many items. So I 开发者_Python百科tend to use the Decorator Pattern for this program. Here is the initial design:

http://img337.imageshack.us/img337/5530/maina.jpg

Can you help me to improve the design?


In object-oriented programming, the decorator pattern is a design pattern that allows new/additional behaviour to be added to an existing object dynamically.

This how wikipedia starts it's article on the decorator pattern.

So the decorator pattern is about adding behaviour to an existing object. And items in a room are not an additional behaviour for that room.

I think, the Composite pattern would be a better choice to build a model for that domain.

(But if you still want a Decorator for your house you may find a better solution here ;-) )


I dont think decorator is the right pattern here. What I'm seeing the design is multiple instances of "is-a" and "has-a" relationships.

  1. An "is-a" relation is a specialization. Examples : "Bungalow" "is-a" "House", "ConcreteRoom1" "is-a" "Room".
    • "is-a" relationships are implemented using inheritance. In some cases, favoring composition over inheritance, "is-a" maybe implemented using decorators.
    • Ideally, the "Room" or "House" constructs must be interfaces (or abstract classes), which define object contracts and base properties
    • The concrete implementations of these interfaces are the actual objects that you will work with.
  2. A "has-a" relationship is a composition. Examples : "House" has "Floors", "Room" has "Items"
    • Generally, a has-a relationship maybe implemented by storing attributes for each object that your class "has".
    • it is always a good idea to store the attributes as a collection of the interfaces - e.g. Room should have List<Item> items

Hope that clarifies the usage expected in your design.


I see a lot of inheritance here. Decorator pattern dictates lesser inheritance and more composition. So you create decorators and embellish your objects at runtime. See Decorator Patter.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号