Strategy Pattern (1)

设计模式原则:

1. 变化的部分进行封装

2. 组合>继承

3. 面向接口编程而不是面向实现编程

策略模式:

  定义一系列算法并将其封装,使其具有通用的调用方法。策略模式让算法的变化与客户端代码使用它的方法相互独立。

Strategy Pattern

示例代码:

namespace Hello
{
//主板抽象类,不变的代码
public abstract class MainBoard
{
public CPU cpu;
public GPU gpu;

public MainBoard() {}

public void RunCPU()
{
cpu.CPUStart();
}

public void RunGPU()
{
gpu.GPUStart();
}

public abstract void ShowCompany();
}
//CPU接口
public interface CPU
{
void CPUStart();
}

public class IntelCPU : CPU
{
public void CPUStart()
{
Console.WriteLine(
"Intel CPU is running!");
}
}

public class AMDCPU : CPU
{
public void CPUStart()
{
Console.WriteLine(
"AMD CPU is running!");
}
}
//GPU接口
public interface GPU
{
void GPUStart();
}

public class NVIDIAGPU : GPU
{
public void GPUStart()
{
Console.WriteLine(
"NVIDIA GPU is running!");
}
}

public class ATIGPU : GPU
{
public void GPUStart()
{
Console.WriteLine(
"ATI GPU is running!");
}
}
//新主板
public class IntelBoard : MainBoard
{
public IntelBoard()
{
cpu
= new IntelCPU();
gpu
= new NVIDIAGPU();
}

public override void ShowCompany()
{
Console.WriteLine(
"Board from Intel.");
}
}
//新主板
public class AMDBoard : MainBoard
{
public AMDBoard()
{
cpu
= new AMDCPU();
gpu
= new ATIGPU();
}

public override void ShowCompany()
{
Console.WriteLine(
"Board from AMD.");
}
}
//开始测试
class Program
{
static void Main(string[] args)
{
MainBoard mainBoard
= new IntelBoard();
mainBoard.ShowCompany();
mainBoard.RunCPU();
mainBoard.RunGPU();

mainBoard
= new AMDBoard();
mainBoard.ShowCompany();
mainBoard.RunCPU();
mainBoard.RunGPU();
}
}
}

  

posted @ 2011-09-13 12:43  Erebus_NET  阅读(122)  评论(0编辑  收藏  举报