zoukankan      html  css  js  c++  java
  • 工厂模式

    public interface Factory {
        public LeiFeng CreateLeiFeng();
    }
    public class LeiFeng {
        public void sweep() {
            System.out.println("sweep");
        }
    
        public void wash() {
            System.out.println("wash");
        }
    
        public void buyRice() {
            System.out.println("buy rice");
        }
    }
    /**
     * Created by tian on 16-5-29.
     * <p>
     * 定义一个用于创建对象的接口,让子类决定实例化哪一个对象。工厂方法使一个类的实例化延迟到其子类
     * 工厂方法模式实现时,客户端需要决定实例化哪一个工厂来实现运算类,选择判断的问题还是存在的,
     * 也就是说,工厂方法把简单工厂的内部逻辑判断移到了客户端代码来进行。想要增加新功能,原来是修改工厂类,
     * 现在是修改客户端。
     */
    public class Main {
        public static void main(String[] args) {
            //简单工厂模式
            LeiFeng studentA = SimpleFactory.CreateLeiFeng("xuesehng");
            LeiFeng zhiyuanzhe = SimpleFactory.CreateLeiFeng("zhiyuanzhe");
            //工厂模式
            Factory factory = new UnderGraduateFactory();
            LeiFeng xuesheng = factory.CreateLeiFeng();
        }
    }
    /**
     * Created by tian on 16-5-29.
     * //简单工厂的实现方法
     */
    public class SimpleFactory {
        public static LeiFeng CreateLeiFeng(String type){
            LeiFeng leiFeng = null;
            switch (type){
                case "xuesheng":
                    leiFeng = new UnderGraduate();
                    break;
                case "zhiyuanzhe":
                    leiFeng = new Volunteer();
            }
            return leiFeng;
        }
    }
    public class UnderGraduate extends LeiFeng{
    
    }
    public class UnderGraduateFactory implements Factory {
        @Override
        public LeiFeng CreateLeiFeng() {
            return new UnderGraduate();
        }
    }
    public class Volunteer extends LeiFeng {
    }
    public class VolunterFactory implements Factory{
    
        @Override
        public LeiFeng CreateLeiFeng() {
            return new Volunteer();
        }
    }
  • 相关阅读:
    Android使用sqlliteOpenhelper更改数据库的存储路径放到SD卡上
    递归实现全排列(一)
    poj_1284_原根
    绝对让你理解Android中的Context
    Java Web---登录验证和字符编码过滤器
    ceph理论及部署配置实践
    ceph for openstack快速部署实施
    php set env
    基于本地iso 搭建的本地yum源 安装部署openldap
    ceph rpm foor rhel6
  • 原文地址:https://www.cnblogs.com/benniaoxuefei/p/5540496.html
Copyright © 2011-2022 走看看