zoukankan      html  css  js  c++  java
  • 设计模式总结3--工厂模式

    简单工厂Simple Factory Pattern

    /*首先要有一个接口和实现这个接口的很多类*/
    public interface Apple {
    
    }
    -----
    public class Apple1 implements Apple{
    
    }
    -----
    public class Apple2 implements Apple{
    
    }
    /*要有一个工厂类,提供方法返回想要的结果 */
    public class AppleFactory {
    
        public static Apple getApple(String name) {
            if("apple1".equalsIgnoreCase(name)) {
                return new Apple1();
            } else if("apple2".equalsIgnoreCase(name)) {
                return new Apple2();
            }
            return null;
        }
    }

    测试

    public class Test {
    
        public static void main(String[] args) {
            /*以前是这样写
                Apple a1 = new Apple1();
                    */
            Apple a1 = AppleFactory.getApple("apple2");
            
        }
    }

    以上这就是简单工厂模式,获取形式与Spring中的ApplicationContext的相似。我们可以写的复杂一点如下

    /* 首先有可供获取的类*/
    public class User {
    
        public void sayHello() {
            System.out.println("hello,user");
        }
    }
    ----
    public class BeanFactory {
    
        /* 
        
        初始版:
        public static Object getBean(String beanName) {
            if("user".equalsIgnoreCase(beanName)) {
                return new User();
            } else if("student".equalsIgnoreCase(beanName)) {
                return new Student();
            }
            return null;
            
        }*/
        
        /* 
        进化版:
            写一个配置文件供读取
            src目录下配置bean.properties文件
            user=com.kaishengit.factory.User
    
        
        
        
        private static Properties prop;
        
        static{
            
            prop = new Properties();
            try {
                prop.load(Factory.class.getClassLoader().getResourceAsStream("bean.properties"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            
        }
        
        
        
        public static Object getBean(String beanName){
            if(prop.containsKey(beanName)){
                String className = prop.getProperty(beanName);
                try {
                    return Class.forName(className).newInstance();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
        */
        
        
        
        /* 
        究极版 :单例模式,放置一个map,验证是否已经存在,存在就返回,不存在就创建一个新的返回
        
            private static Properties prop;
            private static Map<String, Object> map = new HashMap<String, Object>();
        static{
            
            prop = new Properties();
            
            try {
                prop.load(Factory.class.getClassLoader().getResourceAsStream("bean.properties"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            
        }
        
        
        
        public static Object getBean(String beanName){
            
            if(map.containsKey(beanName)){
                return map.get(beanName);
            }else{
                if(prop.containsKey(beanName)){
                    String className = prop.getProperty(beanName);
                    try {
                        return Class.forName(className).newInstance();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }
    }
        */
        
        
        
        
        
        /*究极进化版: 单例模式而是饿汉式  不管你用不用我都创建这个对象    */
        
        private static Properties prop;
        private static Map<String, Object> map = new HashMap<String, Object>();
        
        static{
            
            prop = new Properties();
            
            try {
                prop.load(Factory.class.getClassLoader().getResourceAsStream("bean.properties"));
                /*首先执行静态块里面的程序,获取所有的类的完全限定名然后创建对象 */
                for(Entry<Object, Object> entry : prop.entrySet()){
                    String key = entry.getKey().toString();
                    String value = entry.getValue().toString();
                    
                    Object obj = Class.forName(value).newInstance();
                    map.put(key, obj);
                }
                
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        }
        
        
        
        public static Object getBean(String beanName){
            if(map.containsKey(beanName)){
                return map.get(beanName);
            }
            return null;
        }
        
        
        
        
        
        
        
        
    }

    测试

    public class Test {
    
        public static void main(String[] args) {
            
            User user1 = (User) BeanFactory.getBean("user");
            user.sayHello();
        }
    }

    =====================================================================
    =====================================================================

    工厂方法模式
     比如水果的种类增加,工厂方法模式定义了一个创建对象的接口,但由子类(实现类)决定要实例化的类
    哪一个。工厂方法让类把实例化推迟到子类(实现类)。

    FruitFactory 

    public interface FruitFactory    {    
     
        public Fruit createFruit(String type);    
    } 
    public class AppleFactory implements FruitFactory{    
     
        @Override    
        public Fruit createFruit(String type)    {    
         
            if("hongfushi".equals(type))    {    
                return new apple1();    
            }    else if("meizhou".equals(type))    {    
                return new apple2();    
            }    
             
                return  null;    
        }    
     
    } 

    ===========================================================================
    ===========================================================================
     抽象工厂
    对应于上面的工厂方法模式
    如果一个子工厂产生的是一种产品,比如苹果工厂产苹果,橘子工厂产橘子这样的就是工厂方法模式
    如果一个子工厂产生的是一系列产品,比如热带工厂产生一系列热带水果,亚热带工厂产生一
    系列亚热带水果等就是抽象工厂


    ===========================================================================

  • 相关阅读:
    ExecuteScalar requires the command to have a transaction when the connection assigned to the command is in a pending
    如何从vss中分离程序
    String or binary data would be truncated
    the pop3 service failed to retrieve authentication type and cannot continue
    The POP3 service failed to start because
    IIS Error he system cannot find the file specified _找不到页面
    pku2575Jolly Jumpers
    pku2940Wine Trading in Gergovia
    pku3219二项式系数
    pku1029false coin
  • 原文地址:https://www.cnblogs.com/itliucheng/p/4226746.html
Copyright © 2011-2022 走看看