cxlove / DesignPattern

The example code from head first design patterns for practicing
0 stars 2 forks source link

The Strategy Pattern using Java #3

Open cxlove opened 8 years ago

cxlove commented 8 years ago

RT

cxlove commented 8 years ago

step1: using inherit and override to provide different duck behaviors

if we add a new kind of duck, we need to override all behaviors. if we add a new behavior, we need to implement in all kinds of ducks

cxlove commented 8 years ago

If we use interface for some special behaviors, we also need to implement it in all kinks of ducks.

So the problem is that the duck have some properties for some kinds of ducks is same and others is different.

cxlove commented 8 years ago

step 2: separate fly and sound behavior from duck class, implementing behavior using interface

cxlove commented 8 years ago

Conclusion:

We can separate the behavior into three types:

  1. The first is some behaviors which is stable, it's same for each subclasses. So we can implement it in super class and inherit it directly. Such as "swim" in SimUDuck.
  2. The second is some behaviors which is particular, it's different for each kind of subclasses. So we can define it in super class as a abstract member and implement it in each subclasses directly. Such as "display" in SimUDuck.
  3. The last is some behaviors which have several types. If we implement it in super class and inherit it, we need to override it in some subclasses. If we define it as abstract, we need to implement it in each subclass, the code will be duplicated cross subclasses. It's a trouble to add a new subclasses or a new behavior. So we can extract it from main class into a independent behavior, implement the different types of behavior base on a behavior interface. After that, we can add a behavior instance in main class to use it, each subclass can choose which type of behavior for themselves to assemble.

Principle:

  1. Identify the aspects of your application that vary and separate them from what stays the same.
  2. Program to an interface, not an implementation.
  3. Favor composition over inheritance.