00基础:
抽象;继承;封装;多态;
00原则:
封装变化;多用组合,少用继承;针对接口编程,不针对实现编程;
OO模式:
策略模式--定义算法族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化独立于使用算法的客户
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _1.StrategyPattern { //定义接口 public interface IFLY { string Fly(); } //具体实现算法1 public class RockFly : IFLY { public string Fly() { return "fly like rock"; } } //具体实现算法2 public class NormalFly : IFLY { public string Fly() { return "fly like normal"; } } public class CanotFly : IFLY { public string Fly() { return " can‘t fly"; } } public interface IQuack { string DuckQuack(); } public class QuackBehavior : IQuack { public string DuckQuack() { return "NormalQuack"; } } public class WiredQuackBehavior : IQuack { public string DuckQuack() { return "it‘s sounds like wired annimal"; } } public class CantQuackBehavior : IQuack { public string DuckQuack() { return "no sounds"; } } public class Duck { IFLY f; IQuack quack; public Duck() { f = new NormalFly();//在构造函数中实例化需要的算法 quack = new QuackBehavior(); } public void setFly(IFLY fly) { f = fly;//动态设置需要的算法 } public string DuckFly() { return f.Fly(); } public string DuckQuack() { return quack.DuckQuack(); } } public class MachineDuck { IFLY f; IQuack quack; public MachineDuck() { f = new RockFly(); quack = new CantQuackBehavior(); } public string DuckFly() { return f.Fly(); } public string DuckQuack() { return quack.DuckQuack(); } } }
时间: 2024-10-28 20:54:19