Skip to main content

Strategy Design Pattern


For example, I have a program with an Animal abstract class and two sub-classes Dog and Bird. I want to add new behavior for the class Animal, this is "fly".  Now, I face two approaches to solve this issue:

1. Adding an abstract method "fly" into the class Animal. Then, I force the sub-classes should be implemented this method, something like:

public abstract class Animal{
 //bla bla
 public abstract void fly();
}

public class Bird extends Animal{
 //bla bla
 public void fly(){
 System.out.println("Fly high");
 }
}

public class Dog extends Animal{
 //bla bla
 public void fly(){
  System.out.println("Cant fly");
 }
}

2. Creating an interface with method "fly" inside. The same issue to an abstract class, I force the classes these implement this interface should have a method "fly" inside:

public interface Flyable{
 public void fly();
}
public class Bird implements Flyable{
//bla bla
 public void fly(){
  System.out.println("Fly high");
 }
}

public class Dog implements Flyable{
//bla bla
 public void fly(){
  System.out.println("Cant fly");
 }
}

These approaches are the OOP basics in order to solve the problem when we want to add a new behavior, but there is a disadvantage because all sub-classes are forced to implement this behavior even it doesn't make sense for some classes. And, there is no reused code by using interfaces only.

That is where Strategy Design Pattern can help. The following is an example code:

public interface Flyable{
 public void fly();
}

public class ItFlys implements Flyable{
  public void fly(){
   System.out.println("Fly high");
 }
}

public class CantFly implements Flyable{
  public void fly(){
   System.out.println("Cant fly");
 }
}

public abstract class Animal{
 //bla bla
 Flyable flyType;

 public void tryToFly(){
  flyType.fly();
 }
 public void setFlyAbility(Flyable newFlyType){
  flyType = newFlyType;
 }
}

public class Bird extends Animal{
 //bla bla
 public Bird(){
   flyType = new ItFlys ();
 }
}

public class Dog extends Animal{
 //bla bla
 public Dog (){
   flyType = new CantFly ();
 }
}

This is a diagram that shows the example above:
src: https://www.youtube.com/watch?v=-NCgRD9-C6o&index=3&list=PLF206E906175C7E07

References:

Comments

Popular posts from this blog

How to convert time between timezone in Java, Primefaces?

I use the calendar Primefaces component with timeOnly and timeZone attributes for using only hour format (HH:mm). Like this: <p:calendar id="xabsOvertimeTimeFrom" pattern="HH:mm" timeOnly="true" value="#{data.dateFrom}" timeZone="#{data.timeZone}"/> We can convert the value of #{data.dateFrom} from GMT/UTC time zone to local, conversely, from local time zone to GMT/UTC time zone. Here is my functions: package vn.nvanhuong.timezoneconverter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class TimeZoneConverter { /** * convert a date with hour format (HH:mm) from local time zone to UTC time zone */ public static Date convertHourToUTCTimeZone(Date inputDate) throws ParseException { if(inputDate == null){ return null; } Calendar calendar = Calendar.getInstance(); calendar.setTime(inputDate); int ...

Selenium - Override javascript functions to ignore downloading process

I have got an issue with downloading process on IE 8. This browser blocks my automatic-download functionality on my app so that I could not work with my test case any more after that. In my case, I didn't care about the file is downloaded or not, I just focus on the result after downloading process finished successfully. Therefore, I found a solution to ignore this process so that I can work normally. I use Primefaces, here is the remote command to trigger the download process <p:remoteCommand name="cmdGenerateDocument" actionListener="#{logic.onGenerateDocument}" update="xrflDocumentCreationPanel" oncomplete="clickDownloadButton();"/> The following is my test case: @Test public void shouldUpdateStep6ToWarningIfStep1IsValidAfterFinished(){ MainPage mainPage = new MainPage(); waitForLoading(mainPage.getDriver()); EmployeeDetailPage empDetailPage = new EmployeeDetailPage(); waitForLoading(empDetailPage.getDriver()); e...

Java 8 - Using Functions as Values

The following is a series of posts about "functional programming in Java" which is the result of my understanding by reading the book " Java 8 in Action: Lambdas, Streams, and Functional-style Programming, by Alan Mycroft and Mario Fusco ". 1. Why functional programming? 2. Functional programming in Java 8 3. Java 8 - Using Functions as Values 4. Java 8 - Persistent data structure In general, the phrase "functional-style programming" means the behavior of functions should be like that of mathematical-style functions - no side effects. In programmers' point of views, functions may be used like other values: passed as arguments, returned as result, and stored in data structures . That means we can use the :: operator to create a method reference, and lambda expressions to directly express function values . For example: //method reference Function<String, Integer> strToInt = Integer::parseInt; //lambda expression Comparator<Integer...

Think like a Engineering Manager

Off-boarding Members can leave the company for various reasons, and as a manager, it is important to take action. Hoping for the best is not a strategy. In the case of a low-performing member, I can kindly issue an official warning, set clear objectives for improvement, and re-evaluate the results. If there is a conflict between members, I need to be mindful and go beyond the situation to list our expectations with corresponding actions. Finally, if a member has a big chance to grow at another company, I can have an honest discussion with that member about the trade-offs. Balance at Work As an engineering manager, it is important to balance involvement in meetings and getting your hands dirty on some topics. The goal is to become a companion to teams. Here are my two actions to deal with the situation: Dedicate time for important-but-not-urgent tasks and prioritize them daily. Categorize work into four lines including management, project support, OKRs, and self-study. Management Conduc...