zoukankan      html  css  js  c++  java
  • 设计模式(1)---Factory Pattern

    针对的问题:定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类,工厂模式使其创建过程延迟到子类进行。

    第一步:创建接口

    //创建一个接口
    public interface Shape {
        public abstract void drow();
    }

    第二步:创建接口的实现类

    public class Rectangle implements Shape {
       public void draw() {
          System.out.println("Inside Rectangle::draw() method.");
       }
    }
    public class Square implements Shape {
       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.");
       }
    }

    第三步:定义工程类

    public class ShapeFactory {
        public Shape getShape(String shapeType) {
            if (shapeType.equalsIgnoreCase("CIRCLE")) {
                return new Circle();
            } else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
                return new Rectangle();
            } else if (shapeType.equalsIgnoreCase("SQUARE")) {
                return new Square();
            } else {
                return null;
            }
    
        }
    }

    第四步:编写测试类

    public class FactoryPatternDemo {
    
       public static void main(String[] args) {
          ShapeFactory shapeFactory = new ShapeFactory();
    
          //获取 Circle 的对象,并调用它的 draw 方法
          Shape shape1 = shapeFactory.getShape("CIRCLE");
    
          //调用 Circle 的 draw 方法
          shape1.draw();
    
          //获取 Rectangle 的对象,并调用它的 draw 方法
          Shape shape2 = shapeFactory.getShape("RECTANGLE");
    
          //调用 Rectangle 的 draw 方法
          shape2.draw();
    
          //获取 Square 的对象,并调用它的 draw 方法
          Shape shape3 = shapeFactory.getShape("SQUARE");
    
          //调用 Square 的 draw 方法
          shape3.draw();
       }
    }
  • 相关阅读:
    事件对象
    事件方法on()
    each()遍历
    链接式操作
    理解选取更新范围
    net3.5 无网络环境安装
    visual studio 2017 报错 无法下载安装文件。请检查Internet连接,然后重试
    删除数据恢复数据语句 Oracle
    sqlserver还原数据库(mdf与ldf文件如何还原到SQLserver数据库)
    sqlserver2012卸载
  • 原文地址:https://www.cnblogs.com/excellencesy/p/8576669.html
Copyright © 2011-2022 走看看