JAVA Design Pattern

1 Singleton

One of the simplest design patterns in Java. This pattern involves a single class which is responsible to create an object while making sure that only single object gets created.

Step 1:
Create a Singleton Class:
SingleObject.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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!");
}
}

Step 2:
Get the only object from the singleton class:
SingletonPatternDemo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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();
}
}

Step 3:
Output:

1
Hello World!

2 Factory pattern

1.
Create an interface: Shape.java

1
2
3
public interface Shape {
void draw();
}

  1. Create concrete classes implementing the same interface: Rectangle.java
    1
    2
    3
    4
    5
    6
    7
    public class Rectangle implements Shape {

    @Override
    public void draw() {
    System.out.println("Inside Rectangle::draw() method.");
    }
    }

Square.java

1
2
3
4
5
6
7
public class Square implements Shape {

@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}

Circle.java

1
2
3
4
5
6
7
public class Circle implements Shape {

@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}

  1. Create a Factory to generate object of concrete class based on given information: ShapeFactory.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    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;
    }
    }
  2. Use the Factory to get object of concrete class by passing an information such type: FactoryPatternDemo.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    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();
    }
    }
  3. Output

    1
    2
    3
    Inside Circle::draw() method.
    Inside Rectangle::draw() method.
    Inside Square::draw() method.

3 Iterator Pattern

  1. Create interfaces: Iterator.java
    1
    2
    3
    4
    public interface Iterator {
    public boolean hasNext();
    public Object next();
    }

Container.java

1
2
3
public interface Container {
public Iterator getIterator();
}

  1. Create concrete class implementing the Container interface. This class has inner class NameIterator implementing the Iterator interface: NameRepository.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    public class NameRepository implements Container {
    public String names[] = {"Robert" , "John" ,"Julie" , "Lora"};

    @Override
    public Iterator getIterator() {
    return new NameIterator();
    }

    private class NameIterator implements Iterator {

    int index;

    @Override
    public boolean hasNext() {

    if(index < names.length){
    return true;
    }
    return false;
    }

    @Override
    public Object next() {

    if(this.hasNext()){
    return names[index++];
    }
    return null;
    }
    }
    }
  2. Use the NameRepository to get iterator and print names: IteratorPatternDemo.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    public class IteratorPatternDemo {

    public static void main(String[] args) {
    NameRepository namesRepository = new NameRepository();

    for(Iterator iter = namesRepository.getIterator(); iter.hasNext();){
    String name = (String)iter.next();
    System.out.println("Name : " + name);
    }
    }
    }
  3. Output:

    1
    2
    3
    4
    Name : Robert
    Name : John
    Name : Julie
    Name : Lora

4 Chain of Responsibilities 责任链模式(有求必应)

通过client要求,逐级传递找到责任人,最后作出决断并传回client。
client不需要知道谁处理的,只要知道结果。
击鼓传花:击鼓人:client;花:request;传花的人:request handler
购房折扣申请:
责任人:CEO-Vice President-Manager-Sales
买房者:

definition: 将接受者对象连成一条链,并在链上传递request,知道有一个接受者对象处理它。此方式避免senders与receivers之间的coupling
Imgur
Example Code

缺点:耗时,内存占用大(创建的对象只用了一部分)

5 Strategy 策略模式

将可变部分抽象成算法接口,由客户选择算法。
提供多个方法作为选项。