zoukankan      html  css  js  c++  java
  • 设计模式——简单工厂模式

    简单工厂模式(simple factory method),又叫静态工厂模式(static factory method),简单工厂模式主要思路是一个工厂对象决定创建出哪一类,主要包含工厂类、抽象产品类和具体产品类。

    抽象产品类:

    public interface Product {
        void print();
    }

    具体产品类实现接口或者继承抽象类:

    public class AProduct implements Product {
    
        @Override
        public void print() {
            System.out.println("This is A Product");
        }
    }
    public class BProduct implements Product {
        @Override
        public void print() {
            System.out.println("This is B Product");
        }
    }

    工厂类主要通过选择逻辑实现不同产品的创建:

    public class Factory {
        public static Product createProduct(String type)
        {
            switch (type) {
                case "A":
                    return new AProduct();
                case "B":
                    return new BProduct();
                    default:
                        return null;
            }
    
        }
    }

    主程序调用:

    public class Client {
        public static void main(String []args)
        {
            Factory.createProduct("A").print();
            Factory.createProduct("B").print();
    
    
        }
    }

    结果:

    This is A Product
    This is B Product

    总结:

    客户端只知道传入工厂类的参数,对于如何创建对象不关心:客户端既不需要关心创建细节,甚至连类名都不需要记住,只需要知道类型所对应的参数。

    应用实例:工具类java.text.DateFormat

  • 相关阅读:
    判断arm立即数是否合法的小程序
    一个操作系统的实现:关于ALIGN的若干解释
    一个郁闷的C语言小问题
    test
    浮点数的比较
    一个操作系统的实现:Descriptor 3详解
    一个操作系统的实现:关于CPL、RPL、DPL
    C99可变长数组VLA详解
    SVProgressHUD 用法
    IOS CALayer 详解
  • 原文地址:https://www.cnblogs.com/lbrs/p/13053170.html
Copyright © 2011-2022 走看看