Design Pattern

Design Pattern

Contents:

Types of Design Patterns

Factory Pattern

public interface Shape{
	 void draw();
}
  public class Rectangle implements Shape{
	   @Override
	   public void draw(){
	      System.out.println("Inside Rectangle");
       }
   }
    public class Circle implements Shape{
	   @Override
	   public void draw(){
	      System.out.println("Inside Circle");
       }
    }
    public class ShapeFactory{
	   public Shape getShape(String type){
	      if(type == null){
	         return null;   
	      }
	      if(shape.equalsIgnoreCase("Rectangle")){
             return new Rectangle();
	      }
	      if(shape.equalsIgnoreCase("Circle")){
             return new Circle();
	      }
	      return null
	   }
    }
    public class Demo{
	   ShapeFactory factory = new ShapeFactory();
	   Shape circle = factory.getShape("Circle");
	   circle.draw();
	   Shape rectangle = factory.getShape("Rectangle");
	   rectangle.draw();
    }

Singleton Pattern

    public class SingleObject{
	   private static SingleObject ins = new SingleObject();

	   private SingleObject(){}

	   public static SingleObject getInstance(){
	   	   return ins;
	   }

	   public void show(){
	   	   System.out.println("Hello");
	   }
    }
    public class Demo{
	   public static void main(String[] args){
	       SingleObject obj = SingleObject.getInstance();
	       obj.show();
	   }
    }

MVC Pattern

   public class Student{
       private String id;
       private String name;

       public String getId(){
           return id;
       }

       public String getName(){
           return name;
       }

       public void setId(String id){
           this.id = id;
       }

       public void setName(String name){
           this.name = name;
       }	
    }
    public class StudentView{
	   public void printInfo(String studentName, String studentId){
	        System.out.println("Student: " + studentName);
	        System.out.println("Student ID: " + studentId);
	   }
    }
   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 void setStudentId(String id){
	   	   model.setId(id);
	   }

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

	   public String getStudentId(){
	   	   return model.getId();
	   }

	   public void updateView(){
	   	   view.printInfo(model.getName(), model.getId());
	   }
    }
   public class Demo{
	  public static void main(String[] args){
	      Student model = getStudentFromDatabase();
	      StudentView view = new StudentView();
	      StudentController controller = new StudentController(model,view);

	      controller.updateView();

	      controller.setStudentName("Other name");
	      controller.updateView();
	  }
    }