热门问题
时间线
聊天
视角

策略模式

軟件設計模式 来自维基百科,自由的百科全书

策略模式
Remove ads

计算机编程中,策略模式是一种行为型软件设计模式,它确使可以在运行时选择算法。不再直接的实现一个单一的算法,代码接收运行时指令,选择一个算法家族中的某个算法[1]

Thumb
策略模式的UML类图

概述

策略模式:

  • 定义了一族算法(业务规则);
  • 封装了每个算法;
  • 这族的算法可互换代替(interchangeable)。

结构

Thumb
策略模式的样例UML类图和序列图[1]
Thumb
策略模式的LePUS3图。

示例

C++

下面是C++的例子:

#include <iostream>

using namespace std;

class StrategyInterface {
public:
    virtual void execute() = 0;
};

class ConcreteStrategyA: public StrategyInterface {
public:
    virtual void execute() {
        cout << "Called ConcreteStrategyA execute method" << endl;
    }
};

class ConcreteStrategyB: public StrategyInterface {
public:
    virtual void execute() {
        cout << "Called ConcreteStrategyB execute method" << endl;
    }
};

class Context {
private:
    StrategyInterface *_strategy;

public:
    Context(StrategyInterface *strategy):_strategy(strategy) {
    }

    void set_strategy(StrategyInterface *strategy) {
        _strategy = strategy;
    }

    void execute() {
        _strategy->execute();
    }
};

int main(int argc, char *argv[])
{
    ConcreteStrategyA concreteStrategyA;
    ConcreteStrategyB concreteStrategyB;

    Context contextA(&concreteStrategyA);
    Context contextB(&concreteStrategyB);

    contextA.execute();
    contextB.execute();
    
    contextA.set_strategy(&concreteStrategyB);
    contextA.execute();

    return 0;
}
Remove ads

Java

下面是Java的例子:

// The classes that implement a concrete strategy should implement this
// The context class uses this to call the concrete strategy
interface Strategy {
    void execute();
}

// Implements the algorithm using the strategy interface
class FirstStrategy implements Strategy {
    public void execute() {
        System.out.println("Called FirstStrategy.execute()");
    }
}

class SecondStrategy implements Strategy {
    public void execute() {
        System.out.println("Called SecondStrategy.execute()");
    }
}

// Configured with a ConcreteStrategy object and maintains a reference to a Strategy object
class Context {
    Strategy strategy;

    // Constructor
    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public void execute() {
        this.strategy.execute();
    }
}

//StrategyExample test application
class StrategyExample {
    public static void main(String[] args) {
        Context context;

        // Three contexts following different strategies
        context = new Context(new FirstStrategy());
        context.execute();

        context = new Context(new SecondStrategy());
        context.execute();
    }
}
Remove ads

C#

下面是C#的例子:

using System;

namespace Wikipedia.Patterns.Strategy {
    // The classes that implement a concrete strategy should implement this
    // The context class uses this to call the concrete strategy
    interface IStrategy {
        void Execute();
    }

    // Implements the algorithm using the strategy interface
    class ConcreteStrategyA : IStrategy {
        public void Execute() {
            Console.WriteLine( "Called ConcreteStrategyA.Execute()" );
        }
    }

    class ConcreteStrategyB : IStrategy {
        public void Execute() {
            Console.WriteLine( "Called ConcreteStrategyB.Execute()" );
        }
    }

    // Configured with a ConcreteStrategy object and maintains a reference to a Strategy object
    class Context {
        IStrategy strategy;

        // Constructor
        public Context(IStrategy strategy) {
            this.strategy = strategy;
        }

        public void Execute() {
            strategy.Execute();
        }
    }

    // MainApp test application
    class MainApp {
        static void Main() {
            Context context;

            // Three contexts following different strategies
            context = new Context(new ConcreteStrategyA());
            context.Execute();

            context = new Context(new ConcreteStrategyB());
            context.Execute();
        }
    }
}
Remove ads

Python

下面是Python的例子:

from abc import ABC, abstractmethod

class Strategy(ABC):
    @abstractmethod
    def execute(self): pass

class ConcreteStrategyA(Strategy):
    def execute(self): 
        print("Called ConcreteStrategyA execute method")

class ConcreteStrategyB(Strategy):
    def execute(self): 
        print("Called ConcreteStrategyB execute method")

class Context():
    def __init__(self, strategy):
        self.strategy = strategy
    def execute(self):
        self.strategy.execute()

其执行:

>>> context = Context(ConcreteStrategyA())
>>> context.execute()
Called ConcreteStrategyA execute method
>>> context = Context(ConcreteStrategyB())
>>> context.execute()
Called ConcreteStrategyB execute method
Remove ads

PHP

下面是PHP的例子:

<?php
interface IStrategy {
    public function execute();
}

class ConcreteStrategyA implements IStrategy {
    public function execute() {
        echo "Called ConcreteStrategyA execute method\n";
    }
}

class ConcreteStrategyB implements IStrategy {
    public function execute() {
        echo "Called ConcreteStrategyB execute method\n";
    }
}

class Context {
    var $strategy;

    public function __construct(IStrategy $strategy) {
        $this->strategy = $strategy;
    }

    public function execute() {
        $this->strategy->execute();
    }
}

class StrategyExample {
    public function __construct() {
        $context = new Context(new ConcreteStrategyA());
        $context->execute();

        $context = new Context(new ConcreteStrategyB());
        $context->execute();
    }
}

new StrategyExample;
?>
Remove ads

引用

Loading related searches...

Wikiwand - on

Seamless Wikipedia browsing. On steroids.

Remove ads