Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What design pattern will you choose?

I want to design a class, which contains a procedure to achieve a goal. And it must follow some order to make sure the last method, let's say "ExecuteIt", to behave correctly. in such a case, what design patter will you use ? which can make sure that the user must call the public method according some ordering.

If you really don't know what I am saying, then can you share me some concept of choosing a design patter, or what will you consider while design a class?

like image 273
MemoryLeak Avatar asked Apr 01 '10 09:04

MemoryLeak


2 Answers

I believe you are looking for the Template Method pattern.

like image 58
Oded Avatar answered Oct 02 '22 09:10

Oded


Template Method is what you want. It is one of the oldest, simply a formalization of a way of composing your classes.

http://en.wikipedia.org/wiki/Template_method_pattern

or as in this code sample:

abstract class AbstractParent // this is the template class
{
    // this is the template method that enforces an order of method execution
   final void executeIt()
   {
     doBefore(); // << to be implemented by subclasses
     doInTheMiddle() // also to be implemented by subclasses
     doLast(); // << the one you want to make sure gets executed last
   }

   abstract void doBefore();
   abstract void doInTheMiddle();
   final void doLast(){ .... }
}

class SubA extends AbstractParent
{
   void doBefore(){ ... does something ...}
   void doInTheMiddle(){ ... does something ...}
}

class SubB extends SubA
{
   void doBefore(){ ... does something different ...}
}

But it seems you are fishing for an opportunity to use a pattern as opposed to use a pattern to solve a specific type of problem. That will only lead you to bad software development habits.

Don't think about patterns. Think about how you would go around solving that specific problem without having patterns.

Imagine there were no codified patterns (which is how it was before). How would you accomplish what you want to do here (which is what people did to solve this type of problems.) When you can do that, then you will be in a much better position to understand patterns.

Don't use them as cookie cutters. That is the last thing you want to do.

like image 34
luis.espinal Avatar answered Oct 02 '22 08:10

luis.espinal