Java设计模式---简单工厂模式

2019-12-03  本文已影响0人  Eafrey

简单工厂模式

简单工厂模式又叫做静态工厂方法模式。由一个工厂对象根据传入的参数决定创建哪一种产品(类)的实例。简单工厂模式隐藏了对象的创建逻辑,调用者只需知道它们共同的接口是是什么,从而使软件的结构更加清晰,整个系统的设计也更符合单一职责原则。

简单工厂模式的角色以及对应的职责:

什么时候使用

简单工厂模式可以根据传入的参数实例化相应的对象,适用于以下情景:

一个简单的例子

抽象产品的定义

在这里,我们定义一个Shape:

public interface Shape {
   void draw();
}

具体产品的定义

在这里,我们定义了Shape的三个实现类Rectangle、Square和Circle,它们分别有各自的实现的draw()方法:

public class Rectangle implements Shape {
   @Override
   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
   }
}
public class Square implements Shape {
   @Override
   public void draw() {
      System.out.println("Inside Square::draw() method.");
   }
}
public class Circle implements Shape {
   @Override
   public void draw() {
      System.out.println("Inside Circle::draw() method.");
   }
}

工厂的定义

ShapeFactory可以根据传入的shapeType返回对应的Shape实现类

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 square
      shape3.draw();
   }
}
上一篇 下一篇

猜你喜欢

热点阅读