• 工厂模式学习记录


      工厂模式(Factory Pattern)

      

      1,Shape接口的定义

    package factory;
    
    public interface Shape {
        void draw();
    }    

      2,Circle实现Shape接口

    package factory;
    
    public class Circle implements Shape {
    
        @Override
        public void draw() {
            System.out.println("draw a Circle");
        }
    
    }

      3,Rectangle实现Shape接口

    package factory;
    
    public class Rectangle implements Shape {
    
        @Override
        public void draw() {
            System.out.println("draw a rectangle");
        }
    
    }

      4,Square实现Shape接口

    package factory;
    
    public class Square implements Shape {
    
        @Override
        public void draw() {
            System.out.println("draw a Square");
        }
    
    }

      5,工厂方法类ShapeFactory

    package factory;
    
    public class ShapeFactory {
         static final String CIRCLE="circle";
         static final String SQUARE="square";
         static final String RECTANGLE="rectangle";
        public Shape getShape(String type){
            if(type.equals(CIRCLE)){
                return new Circle();
            }else if(type.equals(RECTANGLE)){
                return new Rectangle();
            }else if(type.equals(SQUARE)){
                return new Square();
            }else{
                return null;
            }
            
        }
    }

      6,工厂的使用Demo

    package factory;
    
    public class FactoryDemo {
        public static void main(String[] args) {
            ShapeFactory factory= new ShapeFactory();
            
            Shape shape=factory.getShape(ShapeFactory.CIRCLE);
            shape.draw();
        }
    }
  • 相关阅读:
    面向对象
    原型链
    HTTP协议
    java连接数据库(jdbc)调用配置文件
    MySQL-学习笔记
    JAVA-集合框架
    JAVA-多线程
    java中的try-catch-finally异常处理(学习笔记)
    ADO.NET增、删、改、查
    C#资源管理器
  • 原文地址:https://www.cnblogs.com/sansyou/p/7793297.html
Copyright © 2020-2023  润新知