我读过“策略对象通常会成为优秀的重量级”(来自可重复使用的面向对象软件的设计模式元素),我想知道如何实现它。我没有在互联网上找到任何例子。
根据这个想法,代码(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);
}
}
}
答案 0 :(得分:7)
我认为要在此处正确实现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);
}
}
在工厂方法中,只有正确的FlyweightIntr
不可用时才会初始化新lstFlyweight
;否则从{{1}}检索。