工厂模式------之三

面试:你懂什么是分布式系统吗?Redis分布式锁都不会?>>>   hot3.png

建立配置文件,fruit.properties,内容如下:

apple=com.gavin.reflect.Apple2
orange=com.gavin.reflect.Orange2

并将该配置文件放在res文件夹下

package com.gavin.reflect;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
/**
 *
 * 而且用户也无法知道一个接口有多少个可以使用的子类,所以我们通过属性文件的形式配置所需要的子类。
 * @author gavin
 *  使用配置文件,实现工厂方法
 *
 * 2013-5-5
 */
class FactoryPatttern
{
    public static void main(String[] a) throws FileNotFoundException, IOException
    {
        Properties pro = getPro();
        String property=pro.getProperty("apple");
        fruit2 f = Factory2.getInstance(property);
        if (f != null)
        {
            f.eat();
        }
    }
    // 操作属性文件类
    public static Properties getPro() throws FileNotFoundException, IOException
    {
        Properties pro = new Properties();
        File f = new File("res/fruit.properties");
        if (f.exists())
        {
            pro.load(new FileInputStream(f));
        } else
        {
            System.out.println("文件不存在");
        }
        return pro;
    }
}

interface fruit2
{
    public abstract void eat();
}

class Apple2 implements fruit2
{
    public void eat()
    {
        System.out.println("Apple");
    }
}

class Orange2 implements fruit2
{
    public void eat()
    {
        System.out.println("Orange");
    }
}




class Factory2
{
    public static fruit2 getInstance(String ClassName)
    {
        fruit2 f = null;
        try
        {
            f = (fruit2) Class.forName(ClassName).newInstance();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return f;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值