我已经读过"策略对象经常做出好的飞重"(来自可重复使用的面向对象软件的设计模式元素),我想知道如何实现它.我没有在互联网上找到任何例子.
遵循这个想法,代码(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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我认为,要在此处正确实现flyweight模式,您的工厂方法应始终返回特定策略的相同实例(如ConcreteStrategyEven),而不是每次都构造一个新实例.
如果我没有弄错,那么说Strategy对象制作好的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);
}
}
Run Code Online (Sandbox Code Playgroud)
在工厂方法中,FlyweightIntr只有在没有正确的新方法时才初始化new ; 否则从中检索lstFlyweight.