zoukankan      html  css  js  c++  java
  • 设计模式(1):工厂模式

    在工厂模式中,我们没有创建逻辑暴露给客户端创建对象,并使用一个通用的接口引用新创建的对象。

    1.创建Shape接口

    public interface Shape {
       void draw();
    }

    2.创建多个Shape实现类(这里创建了3个)

    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.");
       }
    }

    3.创建工厂

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

    4.使用工厂通过传递类型等信息来获取具体类的对象

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

    5.输出结果如下:

    Inside Circle::draw() method.
    Inside Rectangle::draw() method.
    Inside Square::draw() method.
  • 相关阅读:
    前端ajax传数据成功发送,但后端接收不到
    POST 400 (BAD REQUEST)
    chrome浏览器本地文件支持ajax请求的解决方法
    系统可能不会保存你所做的修改 onbeforeunload
    bootstrap 常用class(不定时更新)
    webstrom 一直反复indexing
    setInterval传递参数
    在CentOS 7上安装GitLab
    「Githug」Git 游戏通关流程
    分布式版本控制系统Git——图形化Git客户端工具TortoiseGit
  • 原文地址:https://www.cnblogs.com/zhch1212/p/10185384.html
Copyright © 2011-2022 走看看