new design pattern -- strategy pattern

本文探讨了在没有实际项目应用的情况下学习设计模式的挑战,通过具体案例深入解析了策略模式的运用。作者以鸭子类的飞行行为为例,展示了如何将变化的行为抽象为独立的类,从而提高代码的复用性和灵活性。

for design pattern , i always has an impression that we would not find the advantages and disadvantages if we don't use them in our projects.

i don't have many opportunities to use them  so everytime i learn a design pattern , i just know how to use it , but i can't find that why i should use it , this design pattern are fit for what kind of situation..... 

but i should not stop learning just becuase i don't have this opportunities...

Today , I learn about design pattern --- strategy pattern

just think that: there is a duck super class include serveral functions

1. fly()

2. quack()

and there are serveral classes which are inherited from this super class, that mean all these classes would inherited fly() and quack() functions.

but about fly() function , there maybe serveral way to fly, all the son classes would fly in one of these ways. so every son class would override the fly() function which would reduce the reuse ability of the code. 

So , we can use strategy pattern, we get function which would always changes and abstract them into a class , and all these class would inherited from a interface so we can realise Polypeptide


  
public abstract class Duck
{
public FlyBehavior flyBehavior;

public void SetFlyBehavior(FlyBehavior be)
{
flyBehavior
= be;
}

public void performFly()
{
flyBehavior.fly();
}

public void Sqack()
{
Console.WriteLine(
" ga ga ga . " );
}

}

public interface FlyBehavior
{
void fly();
}

public class FlyWithWings: FlyBehavior
{
public void fly()
{
console.writeline(
" I can fly with my wings. " );
}
}

public class FlyNoWay : FlyBehavior
{
public void fly()
{
console.writeline(
" I can not fly. " );
}
}


public class MallardDuck:Duck
{
public MallarDuck()
{
flyBehavior
= new FlyWithWings();
}
}

public class SimDuck: Duck
{
public SimDuck()
{
flyBehavior
= new FlyNoWay();
}
}

in this way , we just abstract fly function into serveral classes and the class which inherited from Duck class can choose any of this class to perform fly()

we can also use setFlyBehavior() to set fly funtion whenever need.

转载于:https://www.cnblogs.com/huangwj21/archive/2011/06/14/2080841.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值