gpt4 book ai didi

design-patterns - 策略和享元模式

转载 作者:行者123 更新时间:2023-12-04 07:15:01 24 4
gpt4 key购买 nike

我读到“策略对象通常是很好的享元”(来自可重用面向对象软件的设计模式元素),我想知道如何实现这一点。我没有在互联网上找到任何示例。

右下方的代码 (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);
}
}
}

最佳答案

我认为,为了在这里正确实现享元模式,您的工厂方法应该始终返回特定策略的相同实例(如 ConcreteStrategyEven),而不是每次都构造一个新实例。

如果我没记错的话,说 Strategy 对象是好的享元的意思是它们通常不封装任何状态(因为它们代表算法而不是实体)并且可以重用。

这是享元工厂示例的链接: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 中检索。

关于design-patterns - 策略和享元模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2061214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com