Head First Design Patterns: Intro to Design Patterns

OO Basics: Abstraction, Encapsulation, Polymorphism, Inheritance

OO Principles: Encapsulate what varies, Favour composition over inheritance, Program to interfaces, not implementations.

OO Patterns: Strategy – defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

 

public abstract class Duck
{
public IFlyBehavior FlyBehavior { get; set; }
public IQuackBehavior QuackBehavior { get; set; }

public abstract void Display();

public void PerformFly()
{
FlyBehavior.Fly();
}

public void PerformQuack()
{
QuackBehavior.Quack();
}

public void Swim()
{
Console.WriteLine(“All ducks float, even decoys!”);
}

}

public class MallardDuck : Duck
{
public MallardDuck()
{
QuackBehavior = new LoudQuack();
FlyBehavior = new FlyWithWings();
}

override public void Display()
{
Console.WriteLine(“I’m a real Mallard duck”);
}
}

 

public interface IFlyBehavior
{
void Fly();
}

public class FlyWithWings : IFlyBehavior
{
public void Fly()
{
Console.WriteLine(“I’m flying!!”);
}
}

 

public interface IQuackBehavior
{
void Quack();
}

// Name it LoadQuack to avoid conflict with method name
public class LoudQuack : IQuackBehavior
{
public void Quack()
{
Console.WriteLine(“LoudQuack”);
}
}

 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s