Skip to content

Design Pattern

hqzhang edited this page Oct 24, 2017 · 3 revisions
  1. Singleton(just one instance) ===Obj.getInstance()
class SingletonObj {
	   //create an object of SingleObject
	   private static SingletonObj instance = new SingletonObj();
	   //make the constructor private so that this class cannot be
	   //instantiated
	   private SingletonObj(){}
	   //Get the only object available
	   public static SingletonObj getInstance(){
	      return instance;
	   }
	   public void showMessage(){
	      System.out.println("Hello World!");
	   }
	}
	public class Singleton {
	   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
		   SingletonObj object = SingletonObj.getInstance();
	      //show the message
	      object.showMessage();
	   }
	}
  1. factory(wrap several class) ===obj.getSpecificClass(“xxxClass”);
interface Shape { void draw(); }
class Square implements Shape {
  public void draw() {
     System.out.println("Inside Square::draw() method.");
  }
}
class Circle implements Shape {
  public void draw() {
     System.out.println("Inside Circle::draw() method.");
  }
}

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("SQUARE")){
        return new Square();
     }
     return null;
  }
}
public class FactoryDemo  {

	   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");
	      shape1.draw();
	    //get an object of Square and call its draw method.
	      Shape shape3 = shapeFactory.getShape("SQUARE");
	      shape3.draw();
	   }
	}
  1. Iterator new NameRepository().getIterator();
interface Iterator {
	   public boolean hasNext();
	   public Object next();
}
interface Container {
	   public Iterator getIterator();
}

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;
	      }		
	}
}

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

	      for(Iterator iter = new NameRepository().getIterator(); iter.hasNext();){
	         String name = (String)iter.next();
	         System.out.println("Name : " + name);
	      } 	
	   }
	}
  1. Adapter new Audioplay().play(“mediatype”,”filename”);
interface MediaPlayer {  
	   public void play(String audioType, String fileName);
}
interface AdvancedMediaPlayer {	
	   public void playVlc(String fileName);
	   public void playMp4(String fileName);
}

class VlcPlayer implements AdvancedMediaPlayer{ //2
	   @Override
	   public void playVlc(String fileName) {
	      System.out.println("Playing vlc file. Name: "+ fileName);		
	   }
	   @Override
	   public void playMp4(String fileName) {
	      //do nothing
	   }
}
class Mp4Player implements AdvancedMediaPlayer{ //2

	   @Override
	   public void playVlc(String fileName) {
	      //do nothing
	   }
	   @Override
	   public void playMp4(String fileName) {
	      System.out.println("Playing mp4 file. Name: "+ fileName);		
	   }
	}

class MediaAdapter implements MediaPlayer { //1

	   AdvancedMediaPlayer advancedMusicPlayer;
	   public MediaAdapter(String audioType){
	      if(audioType.equalsIgnoreCase("vlc") ){
	         advancedMusicPlayer = new VlcPlayer();			
	      } else if (audioType.equalsIgnoreCase("mp4")){
	         advancedMusicPlayer = new Mp4Player();
	      }	
	   }

	   @Override
	   public void play(String audioType, String fileName) {
	      if(audioType.equalsIgnoreCase("vlc")){
	         advancedMusicPlayer.playVlc(fileName);
	      }else if(audioType.equalsIgnoreCase("mp4")){
	         advancedMusicPlayer.playMp4(fileName);
	      }
	   }
}

class AudioPlayer implements MediaPlayer { //1
	   MediaAdapter mediaAdapter; 
	   @Override
	   public void play(String audioType, String fileName) {		
	      //inbuilt support to play mp3 music files
	      if(audioType.equalsIgnoreCase("mp3")){
	         System.out.println("Playing mp3 file. Name: "+ fileName);			
	      } 
	      //mediaAdapter is providing support to play other file formats
	      else if(audioType.equalsIgnoreCase("vlc") 
	         || audioType.equalsIgnoreCase("mp4")){
	         mediaAdapter = new MediaAdapter(audioType);
	         mediaAdapter.play(audioType, fileName);
	      }
	      else{
	         System.out.println("Invalid media. "+
	            audioType + " format not supported");
	      }
	   }   
}

public class AdapterDemo{           //demo
	   public static void main(String[] args) {
	      AudioPlayer audioPlayer = new AudioPlayer();
	      audioPlayer.play("mp3", "beyond the horizon.mp3");
	      audioPlayer.play("mp4", "alone.mp4");
	      audioPlayer.play("vlc", "far far away.vlc");
	      audioPlayer.play("avi", "mind me.avi");
	   }
	}
  1. MVC new StudentController(new Student(), StudentView());
class Student {
   private String rollNo;
   private String name;
   public String getRollNo() {
      return rollNo;
   }
   public void setRollNo(String rollNo) {
      this.rollNo = rollNo;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

class StudentView {
   public void printStudentDetails(String studentName, String studentRollNo){
      System.out.println("Student: ");
      System.out.println("Name: " + studentName);
      System.out.println("Roll No: " + studentRollNo);
   }
}

public class StudentController {
   private Student model;
   private StudentView view;

   public StudentController(Student model, StudentView view){
      this.model = model;
      this.view = view;
   }

   public void setStudentName(String name){
      model.setName(name);		
   }

   public String getStudentName(){
      return model.getName();		
   }

   public void setStudentRollNo(String rollNo){
      model.setRollNo(rollNo);		
   }

   public String getStudentRollNo(){
      return model.getRollNo();		
   }

   public void updateView(){				
      view.printStudentDetails(model.getName(), model.getRollNo());
   }	
}

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

      //fetch student record based on his roll no from the database
      Student model  = retriveStudentFromDatabase();

      //Create a view : to write student details on console
      StudentView view = new StudentView();

      StudentController controller = new StudentController(model, view);

      controller.updateView();

      //update model data
      controller.setStudentName("John");

      controller.updateView();
   }

   private static Student retriveStudentFromDatabase(){
      Student student = new Student();
      student.setName("Robert");
      student.setRollNo("10");
      return student;
   }
}
  1. Observer new OctalObserver(sub=new Subject());sub.update();
import java.util.ArrayList;
import java.util.List;

class Subject {
   private List<Observer> observers 
      = new ArrayList<Observer>();
   private int state;
   public int getState() {
      return state;
   }
   public void setState(int state) {
      this.state = state;
      System.out.println("setstatus in Subject");
      notifyAllObservers();
   }
   public void attach(Observer observer){
      observers.add(observer);		
   }
   public void notifyAllObservers(){
      for (Observer observer : observers) {
         observer.update();
      }
   } 	
}

abstract class Observer {
   protected Subject subject;
   public abstract void update();
}

class BinaryObserver extends Observer{ //1

   public BinaryObserver(Subject subject){
      this.subject = subject;
      this.subject.attach(this);
   }
   @Override
   public void update() {
      System.out.println( "update in Binaryparty: " 
      + Integer.toBinaryString( subject.getState() ) ); 
   }
}

 class OctalObserver extends Observer{ //2

   public OctalObserver(Subject subject){
      this.subject = subject;
      this.subject.attach(this);
   }

   @Override
   public void update() {
     System.out.println( "update in Octal String: " 
     + Integer.toOctalString( subject.getState() ) ); 
   }
}

public class ObserverDemo {
   public static void main(String[] args) {
	   
      Subject subject = new Subject();
      new OctalObserver(subject);
      new BinaryObserver(subject);

      subject.setState(15);
    
   }
}
  1. strategy new Context(new OperationAdd()).context.executeStrategy(10, 5);
	interface Strategy {
	   public int doOperation(int num1, int num2);
	}
	class OperationAdd implements Strategy{
	   @Override
	   public int doOperation(int num1, int num2) {
	      return num1 + num2;
	   }
	}
	 class OperationSubstract implements Strategy{
	   @Override
	   public int doOperation(int num1, int num2) {
	      return num1 - num2;
	   }
	}

	 class Context {
	   private Strategy strategy;
	   public Context(Strategy strategy){
	      this.strategy = strategy;
	   }

	   public int executeStrategy(int num1, int num2){
	      return strategy.doOperation(num1, num2);
	   }
	}

	public class StrategyDemo {
	   public static void main(String[] args) {
	      Context context = new Context(new OperationAdd());		
	      System.out.println("10 + 5 = " + context.executeStrategy(10, 5));

	      context = new Context(new OperationSubstract());		
	      System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
	   }
	}

8). Template new Football().play();

     abstract class Game {
	   abstract void initialize();
	   abstract void startPlay();
	   abstract void endPlay();

	   //template method
	   public final void play(){
	      //initialize the game
	      initialize();
	      //start game
	      startPlay();
	      //end game
	      endPlay();
	   }
	}
	 class Cricket extends Game {
	   @Override
	   void endPlay() {
	      System.out.println("Cricket Game Finished!");
	   }
	   @Override
	   void initialize() {
	      System.out.println("Cricket Game Initialized! Start playing.");
	   }
	   @Override
	   void startPlay() {
	      System.out.println("Cricket Game Started. Enjoy the game!");
	   }
	}
	 class Football extends Game {
	   @Override
	   void endPlay() {
	      System.out.println("Football Game Finished!");
	   }
	   @Override
	   void initialize() {
	      System.out.println("Football Game Initialized! Start playing.");
	   }
	   @Override
	   void startPlay() {
	      System.out.println("Football Game Started. Enjoy the game!");
	   }
	}

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

	      Game game = new Cricket();
	      game.play();
	      System.out.println();
	      game = new Football();
	      game.play();		
	   }
	}
  1. Bridge new Circle(100,100, 10, new RedCircle()).draw();
interface DrawAPI {
	   public void drawCircle(int radius, int x, int y);
	}
	class RedCircle implements DrawAPI {
	   @Override
	   public void drawCircle(int radius, int x, int y) {
	      System.out.println("Drawing Circle[ color: red, radius: "
	         + radius +", x: " +x+", "+ y +"]");
	   }
	}
	class GreenCircle implements DrawAPI {
	   @Override
	   public void drawCircle(int radius, int x, int y) {
	      System.out.println("Drawing Circle[ color: green, radius: "
	         + radius +", x: " +x+", "+ y +"]");
	   }
	}
	abstract class Shape {
	   protected DrawAPI drawAPI;
	   protected Shape(DrawAPI drawAPI){
	      this.drawAPI = drawAPI;
	   }
	   public abstract void draw();	
	}
	 class Circle extends Shape {
	   private int x, y, radius;

	   public Circle(int x, int y, int radius, DrawAPI drawAPI) {
	      super(drawAPI);
	      this.x = x;  
	      this.y = y;  
	      this.radius = radius;
	   }
	   public void draw() {
	      drawAPI.drawCircle(radius,x,y);
	   }
	}
	public class BridgeDemo {
	   public static void main(String[] args) {
	      Shape redCircle = new Circle(100,100, 10, new RedCircle());
	      Shape greenCircle = new Circle(100,100, 10, new GreenCircle());

	      redCircle.draw();
	      greenCircle.draw();
	   }
	}
  1. Decorator new RedShapeDecorator(new Circle()).draw()
    interface Shape {
	   void draw();
	}
	class Rectangle implements Shape {//1
	   @Override
	   public void draw() {
	      System.out.println("Shape: Rectangle");
	   }
	}
	 class Circle implements Shape {//1

	   @Override
	   public void draw() {
	      System.out.println("Shape: Circle");
	   }
	}
	 abstract class ShapeDecorator implements Shape {//2
	   protected Shape decoratedShape;

	   public ShapeDecorator(Shape decoratedShape){
	      this.decoratedShape = decoratedShape;
	   }
	   public void draw(){
	      decoratedShape.draw();
	   }	
	}
	 class RedShapeDecorator extends ShapeDecorator {//2
	   public RedShapeDecorator(Shape decoratedShape) {
	      super(decoratedShape);		
	   }
	   @Override
	   public void draw() {
	      decoratedShape.draw();	       
	      setRedBorder(decoratedShape);
	   }
	   private void setRedBorder(Shape decoratedShape){
	      System.out.println("Border Color: Red");
	   }
	}

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

	      Shape circle = new Circle();
	      Shape redCircle = new RedShapeDecorator(new Circle());

	      Shape redRectangle = new RedShapeDecorator(new Rectangle());
	      System.out.println("Circle with normal border");
	      circle.draw();

	      System.out.println("\nCircle of red border");
	      redCircle.draw();

	      System.out.println("\nRectangle of red border");
	      redRectangle.draw();
	   }
	}
  1. Visitor new Computer().accept(new ComputerPartDisplayVisitor());
       interface ComputerPart {
	   public void accept(ComputerPartVisitor computerPartVisitor);
	}
	class Keyboard  implements ComputerPart {
	   @Override
	   public void accept(ComputerPartVisitor computerPartVisitor) {
	      computerPartVisitor.visit(this);
	   }
	}
	class Monitor  implements ComputerPart {
	   @Override
	   public void accept(ComputerPartVisitor computerPartVisitor) {
	      computerPartVisitor.visit(this);
	   }
	}
	class Computer implements ComputerPart {	
	   ComputerPart[] parts;
	   public Computer(){
	      parts = new ComputerPart[] {new Keyboard(), new Monitor()};		
	   } 
	   @Override
	   public void accept(ComputerPartVisitor computerPartVisitor) {
	      for (int i = 0; i < parts.length; i++) {
	         parts[i].accept(computerPartVisitor);
	      }
	      computerPartVisitor.visit(this);
	   }
	}
	interface ComputerPartVisitor {
		public void visit(Computer computer);
		public void visit(Keyboard keyboard);
		public void visit(Monitor monitor);
	}
	class ComputerPartDisplayVisitor implements ComputerPartVisitor {
	   @Override
	   public void visit(Computer computer) {
	      System.out.println("Displaying Computer.");
	   }
	   @Override
	   public void visit(Keyboard keyboard) {
	      System.out.println("Displaying Keyboard.");
	   }
	   @Override
	   public void visit(Monitor monitor) {
	      System.out.println("Displaying Monitor.");
	   }
	}
	public class VisitorDemo{
	   public static void main(String[] args) {
	      ComputerPart computer = new Computer();
	      computer.accept(new ComputerPartDisplayVisitor());
	   }
	}
Clone this wiki locally