策略模式——HeadFirst学习笔记

时间:2021-12-22 22:00:42

1、策略模式:

定义了算法族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化独立于使用算法的客户;

2、设计工具箱中解锁的工具:

面向对象设计基础:抽象、封装、多态、继承

面向对象原则:封装变化、都用组合少用继承、针对接口编程,不针对实现编程;

3、样例实现:

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

namespace StrategyPattern
{
public interface FlyBehavor
{
string fly();
}

public class FlyWithWings : FlyBehavor
{
public string fly()
{
return "挥着翅膀的女孩";
}
}

public class FlyNoWay : FlyBehavor
{
public string fly()
{
return "没有翅膀的天使";
}
}

public interface QuackBehavor
{
string quack();
}

public class Quack : QuackBehavor
{
public string quack()
{
return "普通鸭子呱呱的浪叫";
}
}

public class Squeak : QuackBehavor
{
public string quack()
{
return "橡皮鸭子吱吱骚叫";
}
}

public class MuteQuack : QuackBehavor
{
public string quack()
{
return "人家是一个安静的美男子";
}
}

public class Duck
{
protected FlyBehavor m_FlyBehavor;
protected QuackBehavor m_QuackBehavor;

public Duck()
{
}

public void setFlyBehavor(FlyBehavor flyBehavor)
{
m_FlyBehavor = flyBehavor;
}

public string ferformQuack()
{
return m_QuackBehavor.quack();
}

public void setQuackBehavor(QuackBehavor quackBehavor)
{
m_QuackBehavor = quackBehavor;
}

public string performFly()
{
return m_FlyBehavor.fly();
}

public string swim()
{
return "I am swimming!";
}

public virtual string display()
{
return string.Empty;
}
}

public class MallardDuck : Duck
{
public MallardDuck()
{
m_FlyBehavor = new FlyWithWings();
m_QuackBehavor = new Quack();
}

public override string display()
{
return "绿头鸭";
}
}

public class RedHeadDuck:Duck
{
public override string display()
{
return "红头鸭";
}
}

public class RubberDuck : Duck
{
public override string display()
{
return "橡皮鸭";
}
}
}

namespace StrategyPattern
{
class Program
{
public static void print(string str)
{
Console.WriteLine(str);
}

static void Main(string[] args)
{
Duck pDuck = new MallardDuck();
print(pDuck.display());
print(pDuck.ferformQuack());
print(pDuck.performFly());

pDuck.setFlyBehavor(new FlyNoWay());
print(pDuck.performFly());

pDuck.setQuackBehavor(new Squeak());
print(pDuck.ferformQuack());

}
}
}

策略模式——HeadFirst学习笔记