2

現在の状態に応じて、オブジェクトのリストから各オブジェクトで異なるメソッドを呼び出す必要があるステート マシンがあります。基本的には、ステート マシンの各ケース ステートメントにループがあるコードをリファクタリングしようとしています。以下のコードのようになります。ただし、関連するメソッドをリファクタリングされた関数に渡す方法を理解できないようです(言うまでもなく、各アイテムでそれを呼び出す方法がわかりません)

どんな助けでも大歓迎です。

コード例は次のとおりです。

    public class MyOtherType
    {
        public bool Method1()
        { return false; }
        public bool Method2()
        { return false; }
        public bool Method3()
        { return false; }
        public bool Method4()
        { return false; }
    }

    public class MyType
    {
        public enum MyState
        {
            DoSomething1,
            DoSomething2,
            DoSomething3,
            DoSomething4
        }
        private MyState State = MyState.DoSomething1;

        List<MyOtherType> MyListOfObjects = new List<MyOtherType>() { new MyOtherType(), new MyOtherType() };

        private void StateMachine()
        {
            switch (State)
            {
                case MyState.DoSomething1:
                    //How do I pass this in? Do I need to set it up differnetly?
                    Process(() => MyOtherType.Method1());
                    break;
                case MyState.DoSomething2:
                    Process(() => MyOtherType.Method2);
                    break;
                case MyState.DoSomething3:
                    Process(() => MyOtherType.Method3);
                    break;
                case MyState.DoSomething4:
                    Process(() => MyOtherType.Method4);
                    break;
            }
        }

        private void Process(Func<bool> method)
        {
            foreach (MyOtherType item in MyListOfObjects)
            {
                //How do I call the method on each item?
                if (item.method())
                {
                    //Do something
                }
            }
        }
    }
4

2 に答える 2

2

このようなブロックを取り除きswitch、状態ごとの戦略の柔軟なマップを導入することで、特定のメソッドを状態から切り離して、簡単に変更したり、注入したりできるようにすることをお勧めします。

IDictionary<MyState, Func<bool>> strategyMap;

1) 記入してください

 // if idea is to access methods without instance of MyOtherType - 
 // make all methods and class itself static so you can access it
 // like MyOtherType.Method1
 strategyMap = new Dictionary<MyState, Func<bool>>();
 strategyMap.Add(MyState.DoSomething1, myOtherTypeInstance.Method1);

2)適切な戦略を呼び出すのではなく、状態に依存しますswitch(State)

 if (starategyMap.ContainsKey(State))
 {
     // pass in an associated strategy 
     Process(starategyMap[State]);
 }

ご不明な点がございましたらお気軽にお問い合わせください

于 2011-09-09T10:20:01.437 に答える
0

考えられる解決策の 1 つは、メソッドを静的にし、メソッドが操作するクラス参照をパラメーターとして取得することです。

public class MyOtherType
{
    public static bool Method1(MyOtherType instance)
    { 
        return instance == null;  
    }
}
于 2011-09-09T10:26:23.933 に答える