标签: strategy-pattern

复合策略模式 - java - 这段代码有多糟糕?

这个问题是我早期帖子的延续:java中的访问者模式实现 - 这看起来如何?

重构我的代码时我有点困惑.我试图将我的访问者模式(在前一篇文章中解释)转换为复合策略模式.我想做这样的事情:

public interface Rule {
  public List<ValidatonError> check(Validatable validatable);
}
Run Code Online (Sandbox Code Playgroud)

现在,我将定义一个这样的规则:

public class ValidCountryRule  {
  public List<ValidationError> check(Validatable validatable) {
    // invokeDAO and do something, if violation met
    // add to a list of ValidationErrors.
    // return the list.
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,我可以有两个不同类型的对象进行验证.这两个可能是完全不同的:说我有一个商店是Validatable,再一个ScheduleValidatable.现在,如果我写一个看起来像这样的复合:

class Validator implements Rule {
  private List<Rule> tests = new ArrayList<Rule>();

  public void addRule(Rule rule) {
    tests.add(rule);
  }

  public List<ValidationError> check(Visitable visitable) {
    List<ValidationError> list = new ArrayList<ValidationError>(); …
Run Code Online (Sandbox Code Playgroud)

java oop design-patterns rules strategy-pattern

8
推荐指数
2
解决办法
4403
查看次数

模板方法和策略设计模式

这可能是一个新手问题,因为我是设计模式的新手,但我正在查看模板方法和策略DP,它们看起来非常相似.我可以阅读定义,检查UML并查看代码示例,但对我而言,似乎策略模式只是使用模板方法模式,但您恰好将其传递给对象(即组合).

就此而言,模板方法似乎只是基本的OO继承.

我错过了他们差异的一些关键方面吗?我错过了一些关于模板方法的东西,它使它更像是基本的继承吗?

注意:有一个上一篇文章(672083),但更多的是关于什么时候使用它,哪种帮助我得到它更多但我希望有效的我对模式本身的想法.

oop design-patterns strategy-pattern template-method-pattern

8
推荐指数
1
解决办法
1769
查看次数

在应用策略模式时,是否有一种避免某些子类中未使用的方法参数的好方法?

我有以下情况,我有不同类型的销售算法来计算销售价格.FixedSaleStrategy不需要basePrice参数,而所有其他策略实现都需要它.有没有一种避免这种冗余参数的好方法?

public abstract class SalesStrategy
{
    public abstract double GetPrice(double basePrice, double saleAmount);
}
public class AmountOffSale : SalesStrategy
{
    public override double GetPrice(double basePrice, double salesAmount)
    {
        return basePrice - salesAmount;
    }
}
public class FixedPriceSale : SalesStrategy
{
    public override double GetPrice(double basePrice, double salesAmount)
    {
        return salesAmount;
    }
}
Run Code Online (Sandbox Code Playgroud)

c# oop design-patterns strategy-pattern

8
推荐指数
2
解决办法
1831
查看次数

这是装饰者还是策略模式,或者两者都不是?

我有以下界面.

PowerSwitch.java

public interface PowerSwitch {
    public boolean powerOn();
    public boolean powerOff();
    public boolean isPowerOn();
}
Run Code Online (Sandbox Code Playgroud)

上面的接口应该包含可以从中派生出任何其他功能的最小方法集,以便尽可能简单地添加其他PowerSwitch实现.

我想在运行时向PowerSwitch接口添加功能(装饰器做什么),创建一个包含PowerSwitch实例组合的类并添加新方法,如下面的两个toggleOnOff()方法.这样我只需要实现两次切换方法,它将适用于所有PowerSwitch实现.

这被认为是一种好/坏的做法吗?如果不好,还有其他建议吗?

它并不真正符合装饰器模式,因为它增加了额外的方法.它是策略模式还是组合模式?或者它有另一个模式名称?有"界面装饰"这样的东西吗?

PowerSwitchDecorator.java

public class PowerSwitchDecorator {
    private PowerSwitch ps;

    public PowerSwitchDecorator(PowerSwitch ps) {
        this.ps = ps;
    }

    public void toggleOnOff(int millis) throws InterruptedException{
        powerOn();
        Thread.sleep(millis);
        powerOff();
    }

    public void toggleOnOff(){
    powerOn();
    powerOff();
    }

    public boolean powerOn() {
        return ps.powerOn();
    }

    public boolean powerOff() {
        return ps.powerOff();
    }

    public boolean isPowerOn() {
        return ps.isPowerOn();
    }
}
Run Code Online (Sandbox Code Playgroud)

java design-patterns decorator strategy-pattern

8
推荐指数
2
解决办法
733
查看次数

首先设计模式 - 战略模式 - Python

这是我第一次尝试战略设计模式.

我没有使用Python的架构经验,因此欢迎提出建设性意见.

我将此发布到Stack-Over-Flow,因为我觉得今天早上它可以作为一个健全性检查.显然,据说我没有为这个线程提供足够的上下文(可怕的验证短语),所以我将不得不像鸭子那样使用Quack.

嘎嘎,嘎嘎,嘎嘎:-)

#!/usr/bin/env python

"""
    Head First Design Patterns - Strategy Pattern
    My attempt to implement the Strategy Pattern, described in Chapter 1.

    Sanity Warning:  I am currently learning Python, so please don't expect the
    exquisite design, planning, construction, and execution of the Curiosity mission.

    Expect Ducks... Quacking...

    Design Principle: "Favour composition over inheritance" 

    To the Pythonista community: What is the most elegant, readable, and simplest way
    of implementing the HFDP Strategy Pattern?
"""

import abc

"""

Abstract …
Run Code Online (Sandbox Code Playgroud)

python design-patterns strategy-pattern

8
推荐指数
0
解决办法
1580
查看次数

如何在Go中实施战略模式?

这是我要解决的一般问题:

  1. 一组软件包从一个源收集数据并将其发送到多个通道.
  2. 第二组软件包从许多渠道收集数据并将其写入一个来源.这组包需要从多种格式转换数据.

这似乎是战略模式的完美案例,但我不确定如何最好地在Go中完成这项工作.

design-patterns strategy-pattern go

8
推荐指数
1
解决办法
3663
查看次数

战略设计模式,泛型和类型安全

我想创建以下策略模式与Factory结合,但我希望它是类型安全的.到目前为止我做了以下事情:

public interface Parser<T> {

    public Collection<T> parse(ResultSet resultSet);

}


public class AParser implements Parser<String> {

    @Override
    public Collection<String> parse(ResultSet resultSet) {
             //perform parsing, get collection
        Collection<String> cl = performParsing(resultSet); //local private method
        return cl;
    }
}

public class ParserFactory {

    public enum ParserType {
        APARSER
    }


    public static <T> Parser<T> createParser(ParserType parserType) {


        Parser<?> parser = null;
        switch (parserType) {
        case APARSER:
            parser = new AParser();
            break;
        }
            //unchecked cast happens here
        return (Parser<T>) parser;
    }
}


public class …
Run Code Online (Sandbox Code Playgroud)

java generics strategy-pattern factory-pattern

8
推荐指数
2
解决办法
2938
查看次数

如何用std :: function在C++中实现策略模式

我正在讨论在C++中实现策略模式的最佳方法.到目前为止,我一直使用标准方式,其中上下文具有指向基本策略类的指针,如下所示:

 class AbstractStrategy{
 public:
     virtual void exec() = 0;
 }
 class ConcreteStrategyA{
 public:
     void exec();
 }
 class ConcreteStrategyB{
 public:
     void exec();
 }

 class Context{
 public:
     Context(AbstractStrategy* strategy):strategy_(strategy){}
     ~Context(){
          delete strategy;
       }
      void run(){
           strategy->exec();
      }
 private:
     AbstractStrategy* strategy_;
Run Code Online (Sandbox Code Playgroud)

由于有指向对象的指针可能会导致不良行为,我一直在寻找一种更安全的方式来实现这种模式,我发现这个问题在哪里std::function被提议作为处理这种模式的更好方法.

有人可以更好地解释一下如何std::function运作,也许有一个战略模式的例子?

c++ pointers strategy-pattern c++11 std-function

8
推荐指数
2
解决办法
1942
查看次数

在c#战略模式和代表之间有什么区别?

我一直在研究策略模式实现示例,在我看来它们与c#delegates非常相似.我看到的唯一区别是策略模式实现不需要显式声明委托.

但除此之外,它们似乎都指向需要特定签名的函数,它们都可以用于确定在运行时执行的内容.

我错过了一个更明显的区别吗?

我想一个相关的问题是,如果它们相似,那么使用一个优于另一个的优势是什么?

c# delegates strategy-pattern

7
推荐指数
1
解决办法
2793
查看次数

策略模式还是界面?

我正在寻找抽象一个辅助方法。该方法需要能够接收一个对象,根据对象的类型对其执行操作,并返回一个值。这样做会更好吗:

interface ICanDo
{
 string DoSomething();
}

string DoThings(ICanDo mything)
{
 return mything.DoSomething();
}
Run Code Online (Sandbox Code Playgroud)

或者最好做这样的事情:

interface IStrategy
{
 string DoSomething(object o);
}

string DoThings(object mything, IStrategy strategy)
{
 return strategy.DoSomething(mything);
}
Run Code Online (Sandbox Code Playgroud)

后者是否甚至使用策略模式,因为该策略没有内置到类中?

有没有更好的方法来做到这一点我没有想到?将策略构建到类中,为任何需要运行 DoThings 的类使用包装器会更好吗?

抱歉——我对这种模式很陌生,并试图弄清楚在哪里以及如何最好地使用它。

这就是我最终整理出来的。我不确定这是否遵循良好的开发原则。

class IndexWrapper
{
    public interface IDocumentable
    {
        Document BuildDocument();
    }

    public interface IDocumentBuilder
    {
        Type SupportedType { get; }

        Document BuildDocument(object o);
    }

    public class StringDocumentBuilder : IDocumentBuilder
    {
        public Type SupportedType { get { return typeof(string); } }

        public Document BuildDocument(object o) …
Run Code Online (Sandbox Code Playgroud)

design-patterns strategy-pattern c#-4.0

7
推荐指数
1
解决办法
3225
查看次数