我读过“策略对象通常会成为很好的蝇量级”(来自可重用面向对象软件的设计模式元素),我想知道如何实现这一点。我在互联网上没有找到任何例子。
下面的代码(C#)是否符合这个想法?
Thanks!
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);
}
}
}
我认为要在这里正确实现享元模式,您的工厂方法应该始终返回特定策略的相同实例(例如ConcreteStrategyEven
)而不是每次都构建一个新实例。
如果我没记错的话,说策略对象是好的享元的要点是它们通常不封装任何状态(因为它们代表算法而不是实体)并且可以重用。
以下是 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
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)