栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

15.7类的生命周期&&15.8工厂设计模式(血干JAVA系类)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

15.7类的生命周期&&15.8工厂设计模式(血干JAVA系类)

这里写目录标题
  • 15.7类的生命周期
  • 15.8工厂设计模式
    • 15.8.1将反射应用在工厂模式上
    • 15.8.2结合属性文件的工厂模式
        • 【例15.29]属性操作类
        • 【例15.30】测试程序

15.7类的生命周期

15.8工厂设计模式 15.8.1将反射应用在工厂模式上

package file;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface Fruit
{
	public void eat();
}
class Apple implements Fruit
{
	public void eat()
	{
		System.out.println("吃苹果");
	}
}
class Orange implements Fruit
{
	public void eat() 
	{
		System.out.println("吃橘子");
	}
}
class Factory
{
	public static Fruit getinstance(String path)
	{
		Fruit f = null;
		try 
		{
			f = (Fruit) Class.forName(path).newInstance();
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		return f;
	}
}
public class demo 
{
	public static void main(String[] args) throws Exception
	{		
		Fruit f =Factory.getinstance("file.Apple");
		if(f!=null)
		{
			f.eat();
		}
	}
}

15.8.2结合属性文件的工厂模式

【例15.29]属性操作类 【例15.30】测试程序
class Init
{
	public static Properties getProperties()
	{
		Properties pro = new Properties();
		File f = new File("d:"+File.separator+"fruit.properties");
		try 
		{
			if(f.exists())
			{
				pro.load(new FileInputStream(f));
			}
			else
			{
				pro.setProperty("apple", "file.Apple");
				pro.setProperty("orange", "file.Orange");
				pro.store(new FileOutputStream(f), "不存在文件,store的");
			}
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		return pro;
	}
}
public class demo 
{
	public static void main(String[] args) throws Exception
	{		
		Properties pro = Init.getProperties();
		Fruit f =Factory.getinstance(pro.getProperty("orange"));
		if(f!=null)
		{
			f.eat();
		}
	}
}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/992344.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号