简体   繁体   English

什么设计模式适合将属性应用于改变其行为的类?

[英]What design pattern is good for applying attributes to a class that changes its behavior?

I am trying to find the best way to structure my project.我正在努力寻找构建项目的最佳方式。 What I would like to do is have a "Structure", which is made of multiple "part".我想做的是有一个“结构”,它由多个“部分”组成。 These parts also will have separate attributes, for example it could be spinning, hovering, vibrating, jumping, shaking, growing, accelerating.这些部件也将具有单独的属性,例如它可以是旋转、悬停、振动、跳跃、摇晃、生长、加速。

So for example, I might have a "structure" called human that is made of 6 "parts".例如,我可能有一个称为人类的“结构”,它由 6 个“部分”组成。 I am going to set each part to one of the available options, so in this case, 2 parts are going to be arms, 2 parts are going to be legs, one part is a torso, and one part is a head.我要将每个部分设置为可用选项之一,因此在这种情况下,2 个部分将是手臂,2 个部分将是腿,一个是躯干,一个是头部。 Now, I want to be able to apply the attribute spinning to one of the parts, the arm.现在,我希望能够将属性旋转应用于其中一个部分,即手臂。 So now I should have a human with a spinning arm.所以现在我应该有一个有旋转手臂的人。

Additionally, I would like other people to be able to create their own cusom attributes, structures, and parts.此外,我希望其他人能够创建自己的自定义属性、结构和部件。

I would like to get an idea on how I should structure my code, and apply an attribute to a part.我想知道我应该如何构建我的代码,并将属性应用于部件。 Additionally, what design pattern would be good for this?此外,什么设计模式对此有好处?

The requirement is to have a single interface for a composition of various objects / components.要求是具有用于组合各种对象/组件的单个接口。

There are 2 suitable design patterns for this requirement.有 2 种适合此要求的设计模式。

  1. Facade ( https://dzone.com/refcardz/design-patterns?chapter=17 )外观( https://dzone.com/refcardz/design-patterns?chapter=17
  2. Composite Object ( https://dzone.com/refcardz/design-patterns?chapter=15 )复合对象 ( https://dzone.com/refcardz/design-patterns?chapter=15 )

Facade pattern can be used when the way in which the internal components are assembled must be abstracted.当内部组件的组装方式必须抽象时,可以使用外观模式。

Composite object pattern can be used when the assembly of the components must be advertised.当必须通告组件的装配时,可以使用复合对象模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM