zoukankan      html  css  js  c++  java
  • 创建型设计模式(工厂模式)

    在工厂模式中,我们创建对象而不将创建逻辑暴露给客户端。

    首先,我们设计一个接口来表示Shape。

    public interface Shape {
       void 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.");
       }
    }
    

    核心工厂模式是一个Factory类。以下代码显示了如何为Shape对象创建Factory类。

    ShapeFactory类基于传递给getShape()方法的String值创建Shape对象。如果String值为CIRCLE,它将创建一个Circle对象。

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

      以下代码具有main方法,并且它使用Factory类通过传递类型等信息来获取具体类的对象。

    public class Main {
    
       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();
       }
    }
    

      

      

      

  • 相关阅读:
    【Vue教程系列:第一篇】Win7 搭建Vue开发环境
    MVC 之 WebAPI 系列二
    MVC 之 WebAPI 系列一
    Javascript 截取2位小数
    Javascript 处理时间大全
    SpringBoot是如何动起来的?
    超全、超详的Spring Boot配置讲解笔记
    Java数据结构-ArrayList最细致的解析笔记
    Redis 到底是怎么实现“附近的人”这个功能的?
    02--Java Jshell的使用 最适合入门的Java教程
  • 原文地址:https://www.cnblogs.com/echo-ling/p/7475950.html
Copyright © 2011-2022 走看看