我需要一个设计模式吗?

时间:2017-02-24 13:36:13

标签: oop design-patterns

我有一个相当理论上的问题。

例如,我有一类对象 - 比如Table。这张桌子可以用不同的颜色着色 - 红色,蓝色和黄色。如果表之前没有着色,结果很清楚。否则,以下规则正在起作用:

red + yellow --> orange
blue + yellow --> green
red + blue --> purple
red + blue + yellow --> brown

实现这一目标的最好和最优雅的方法是什么?这种情况有什么设计模式吗?我的变体可能过于简单了:

public class Table{

private boolean isRed;
private boolean isBlue;
private boolean isYellow;

     public String colorRed(){
         isRed = true;
         if (isBlue && isYellow) 
               return "brown";
         if (isBlue)
               return "purple";
         if (isYellow)
               return "orange";
         return "red";
     }
     //... the same for other colors
}

1 个答案:

答案 0 :(得分:0)

我建议state machine

enter image description here

建议实施:

interface IColorState {
        IColorState AddBlue();
        IColorState AddRed();
        IColorState AddYellow();
}

class BlueState: IColorState {
     public override AddBlue() {return new BlueState()}
     public override AddRed() {return new PurpleState()}
     public override AddYellow() {return new GreenState()}
}

class YellowState: IColorState {...}

class RedState: IColorState {...}

class PurpleState: IColorState {
     public override AddBlue() {return new PurpleState()}
     public override AddRed() {return new PurpleState()}
     public override AddYellow() {return new BrownState()}
}