2010-01-13 162 views
1

我讀過「策略對象通常會產生很好的flyweights」(可重用面向對象軟件的設計模式元素),我想知道如何實現它。我在互聯網上沒有找到任何例子。策略和享元模式

下面的代碼(C#)正確嗎?

謝謝!

using System; 
using System.Collections.Generic; 

namespace StrategyFlyweight 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Client client = new Client(); 
      for(int i = 1; i <= 10;i++) 
      { 
       client.Execute(i); 
      } 
      Console.ReadKey(); 
     } 
    } 

    public interface IStrategy 
    { 
     void Check(int number); 
    } 

    public class ConcreteStrategyEven : IStrategy 
    { 
     public void Check(int number) 
     { 
      Console.WriteLine("{0} is an even number...", number); 
     } 
    } 

    public class ConcreteStrategyOdd : IStrategy 
    { 
     public void Check(int number) 
     { 
      Console.WriteLine("{0} is an odd number...", number); 
     } 
    } 

    public class FlyweightFactory 
    { 
     private Dictionary<string, IStrategy> _sharedObjects = new Dictionary<string, IStrategy>(); 

     public IStrategy GetObject(int param) 
     { 
      string key = (param % 2 == 0) ? "even" : "odd"; 

      if (_sharedObjects.ContainsKey(key)) 
       return _sharedObjects[key]; 
      else 
      { 
       IStrategy strategy = null; 
       switch (key) 
       { 
        case "even": 
         strategy = new ConcreteStrategyEven(); 
         break; 
        case "odd": 
         strategy = new ConcreteStrategyOdd(); 
         break; 
       } 
       _sharedObjects.Add(key, strategy); 
       return strategy; 
      } 
     } 
    } 

    public class Client 
    { 
     private IStrategy _strategy; 
     private FlyweightFactory _flyweightFactory = new FlyweightFactory(); 

     public void Execute(int param) 
     { 
      ChangeStrategy(param); 
      _strategy.Check(param); 
     } 

     private void ChangeStrategy(int param) 
     { 
      _strategy = _flyweightFactory.GetObject(param); 
     } 
    } 
} 

回答

7

我認爲正確這裏實現輕量級的模式,你的工廠方法應該總是返回一個特定策略的同一個實例(如ConcreteStrategyEven),而不是每次都構建新的實例。

如果我沒有弄錯,說策略對象使Flyweights好的一點是,它們通常不封裝任何狀態(因爲它們代表算法而不是實體)並且可以重複使用。

以下是Flyweight工廠示例的鏈接:http://www.java2s.com/Code/Java/Design-Pattern/FlyweightFactory.htm。注意:此部分,尤其是:

public synchronized FlyweightIntr getFlyweight(String divisionName) { 
    if (lstFlyweight.get(divisionName) == null) { 
     FlyweightIntr fw = new Flyweight(divisionName); 
     lstFlyweight.put(divisionName, fw); 
     return fw; 
    } else { 
     return (FlyweightIntr) lstFlyweight.get(divisionName); 
    } 
    } 

在這裏的工廠方法,新FlyweightIntr只有初始化如果正確的一個不可用;否則它從lstFlyweight檢索。

+0

這就是這個位,對不對? 'if(_sharedObjects.ContainsKey(key))return _sharedObjects [key];'那肯定是懶惰的初始化/單例。 – 2010-01-14 00:30:00

+0

啊,你是對的 - 當我第一次讀它時,我認爲'key'是整數,他正在爲每一個初始化一個新的策略。那麼,希望我的回答無論如何都是有幫助/有用的。 – danben 2010-01-14 01:30:19

+0

是的,這是,謝謝 – Fabio 2010-01-15 01:35:28