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);
}
}
}
這就是這個位,對不對? 'if(_sharedObjects.ContainsKey(key))return _sharedObjects [key];'那肯定是懶惰的初始化/單例。 – 2010-01-14 00:30:00
啊,你是對的 - 當我第一次讀它時,我認爲'key'是整數,他正在爲每一個初始化一個新的策略。那麼,希望我的回答無論如何都是有幫助/有用的。 – danben 2010-01-14 01:30:19
是的,這是,謝謝 – Fabio 2010-01-15 01:35:28