Skip to main content

Some popular design patterns

Singleton design pattern


This pattern makes sure only one object is created and used though out the system.

Create a static instance in the single class

public class SingleObject {

   //create an object of SingleObject
   private static SingleObject instance = new SingleObject();

   //make the constructor private so that this class cannot be
   //instantiated
   private SingleObject(){}

   //Get the only object available
   public static SingleObject getInstance(){
      return instance;
   }

   public void showMessage(){
      System.out.println("Hello World!");
   }
}

Use this instance through the system.

public class SingletonPatternDemo {
   public static void main(String[] args) {

      //illegal construct
      //Compile Time Error: The constructor SingleObject() is not visible
      //SingleObject object = new SingleObject();

      //Get the only object available
      SingleObject object = SingleObject.getInstance();

      //show the message
      object.showMessage();
   }
}



Factory design pattern


This pattern helps to create the object without exposing the creation logic to the client and refer to newly created object using a common interface.

The design pattern distinguishes different object type via the parameter.

public class ShapeFactory {
 
   //use getShape method to get object of type shape 
   public Shape getShape(String shapeType){
      if(shapeType == null){
         return null;
      }  
      if(shapeType.equalsIgnoreCase("CIRCLE")){
         return new Circle();
         
      } else if(shapeType.equalsIgnoreCase("RECTANGLE")){
         return new Rectangle();
         
      } else if(shapeType.equalsIgnoreCase("SQUARE")){
         return new Square();
      }
      
      return null;
   }
}

public class FactoryPatternDemo {

   public static void main(String[] args) {
      ShapeFactory shapeFactory = new ShapeFactory();

      //get an object of Circle and call its draw method.
      Shape shape1 = shapeFactory.getShape("CIRCLE");

      //call draw method of Circle
      shape1.draw();

      //get an object of Rectangle and call its draw method.
      Shape shape2 = shapeFactory.getShape("RECTANGLE");

      //call draw method of Rectangle
      shape2.draw();

      //get an object of Square and call its draw method.
      Shape shape3 = shapeFactory.getShape("SQUARE");

      //call draw method of circle
      shape3.draw();
   }
}

Comments

Popular posts from this blog

PHP json_encode return empty array [] instead of empty object {}

Problem: Get below array for example.  $status = array ( "message" => "error" , "club_id" => $_club_id , "status" => "1" , "membership_info" => array (), ); This array will be encoded in json format echo json_encode($status); This function return json: {"message":"error","club_id":275,"status":"1","membership_info": [] } Notice the empty array [], it is not consistent, it should be an empty object {} {"message":"error","club_id":275,"status":"1","membership_info": {} } The cause: This problem is caused by the called function array(), which yields an empty array [] Solution: There are 2 solutions for this issue: Solution 1: Call new stdClass instead of array(), stdClass generates an empty object {} Solution 2: The above solution is complex in case there are plenty of arr...

Command Prompt VS 2010: Fix MSVCRT.lib(MSVCR100.dll) : error LNK2005: xxx already defined in LIBCMT.lib(xxx.obj)

One of my task is to use Command Prompt of Visual Studio 2010 to evaluate the assignments of students. This assignment is about pointer and memory management in C++. The students are required to use new and delete operator in C++ to manage the memory and they need to ensure that the number of new callings must be equal to the number of delete callings. I overload the new and delete operator, build it into a static library (.lib file) and require student to use this .lib file when implementing the assignment. There is no problem when building the .lib file in VS 2010 project, but there are errors when compile the source code if I link the source code to the above static .lib file. Here is the format of error: MSVCRT.lib(MSVCR100.dll) : error LNK2005: xxx already defined in LIBCMT.lib(xxx.obj) Fortunately, I found 2 ways to fix this error on the internet. The first one is to remove the default lib when compiling the source code, it's libcmt.lib, because this libcmt.lib alread...

Fix cross domain in ajax request

Follow this sample ajax request $.ajax({    "type": 'POST',    "url": url,     "crossDomain": true,    "data": params,    "dataType": 'json',    "async": false,    "success": function(data){ done_fn(data, is_test);    },    "error": function (jqXHR) { var data = $.parseJSON(jqXHR.responseText); $("#results").text(data.message);    } }); The keys are crossDomain: true and async: false Hope to help many people.