










VS 2008
一个类的某个行为可能有多种实现策略,可以将这个行为提取出来定义为接口,那么就可以提供这个接口的多个实现。这些类(策略)可以相互替换而不影响客户端代码。
1. 模式UML图

2. 应用
考虑图书折扣出售的例子,分为普通折扣价,和黄金折扣价。对于售书商来说,这两种折扣就是图书打折出售的两种策略。

IDiscountStrategy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.Strategy.BLL {
public interface IDiscountStrategy {

double CalculatePrice(double price);
}
}

CommonDiscountStrategy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.Strategy.BLL {
public class CommonDiscountStrategy : IDiscountStrategy {

IDiscountStrategy Members
}
}

GoldenDiscountStrategy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.Strategy.BLL {
public class GoldenDiscountStrategy : IDiscountStrategy {

IDiscountStrategy Members
}
}

Book.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.Strategy.BLL {
public class Book {

private double price;

public Book(double price) {
this.price = price;
}

public double GetPriceAfterDiscount(IDiscountStrategy strategy) {
return strategy.CalculatePrice(this.price);
}
}
}

Client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DesignPattern.Strategy.BLL;

namespace DesignPattern.Strategy {
class Program {
static void Main(string[] args) {

Book book1 = new Book(100);
double commonPrice = book1.GetPriceAfterDiscount(new CommonDiscountStrategy());
Console.WriteLine("Common price is {0}", commonPrice.ToString());

double goldenPrice = book1.GetPriceAfterDiscount(new GoldenDiscountStrategy());
Console.WriteLine("Golden price is {0}", goldenPrice.ToString());
}
}
}

Output

此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。