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.
  • 相关阅读:
    报错:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1
    Flink 集群安装配置
    配置Flink依赖的pom文件时报错:flink-clients_2.11 & flink-streaming-java_2.11
    解析流中的Xml文件时,报错:java.net.MalformedURLException: no protocol
    kafka产生的数据通过Flume存到HDFS中
    kafka服务自动关闭
    Flink安装启动
    hadoop长时间运行后,stop-all.sh报错
    Linux环境下配置maven环境
    vue2 自定义时间过滤器
  • 原文地址:https://www.cnblogs.com/zhch1212/p/10185384.html
Copyright © 2011-2022 走看看