當一個問題需要的算法比較多,並且需要可能需要在不同的時候使用不同的算法。這個問題就可以使用策略模式來解決。
策略模式的主要內容就是將不同的算法都封裝成不同的類,然後通過一個類似於工廠的類來調用。
c#實現
有一個算法策略完全抽象類 strage
下面的三個算法都是override 這個strage裏面的方法
再通過一個content類來組裝
最後再客戶端中調用(main)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
abstract class strage
{
public abstract void AlgorithmInterface();
}
class SolutionA : strage
{
public override void AlgorithmInterface()
{
Console.WriteLine("使用算法A");
}
}
class SolutionB : strage
{
public override void AlgorithmInterface()
{
Console.WriteLine("使用算法B");
}
}
class SolutionC : strage
{
public override void AlgorithmInterface()
{
Console.WriteLine("使用算法C");
}
}
class Context
{
strage newStrage;
public Context(strage s)
{
this.newStrage = s;
}
public void ContextInterface()
{
this.newStrage.AlgorithmInterface();
}
}
class Program
{
static void Main(string[] args)
{
strage newstrage = new SolutionB();
Context context = new Context(newstrage);
context.ContextInterface();
Console.ReadLine();
}
}
}
Java實現
package Demo1;
abstract class strage{
public abstract void algorithmSolution();
}
class SolutionA extends strage{
@Override
public void algorithmSolution(){
System.out.println("使用算法A來解決");
}
}
class SolutionB extends strage{
@Override
public void algorithmSolution(){
System.out.println("使用算法B來解決");
}
}
class SolutionC extends strage{
@Override
public void algorithmSolution(){
System.out.println("使用算法C來解決");
}
}
class Content{
strage newStrage;
public Content(strage s){
this.newStrage = s;
}
public void AlgroithmSolution(){
this.newStrage.algorithmSolution();
}
}
public class StrageModel {
public static void main(String[] args) {
strage s = new SolutionA();
Content content = new Content(s);
content.AlgroithmSolution();
}
}
測試結果