zoukankan      html  css  js  c++  java
  • JAVA基础--工厂模式

    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 className){
    		Fruit f = null ;
    		if("apple".equals(className)){	// 判断是否要的是苹果的子类
    			f = new Apple() ;
    		}
    		if("orange".equals(className)){	// 判断是否要的是橘子的子类
    			f = new Orange() ;
    		}
    		return f ;
    	}
    };
    public class InterfaceCaseDemo05{
    	public static void main(String args[]){
    		Fruit f = Factory.getInstance(args[0]) ;	// 实例化接口
    		if(f!=null){	// 判断是否取得实例
    			f.eat() ;
    		}
    	}
    };
    
    package org.lxh.demo15.factorydemo02 ;
    import java.util.Properties ;
    import java.io.File ;
    import java.io.FileOutputStream ;
    import java.io.FileInputStream ;
    interface Fruit{
    	public void eat() ;	// 吃水果
    }
    class Apple implements Fruit{
    	public void eat(){			// 覆写eat()方法
    		System.out.println("** 吃苹果");
    	}
    };
    class Orange implements Fruit{
    	public void eat(){
    		System.out.println("** 吃橘子") ;
    	}
    };
    class Init{
    	public static Properties getPro(){
    		Properties pro = new Properties() ;
    		File f = new File("d:\fruit.properties") ;	// 找到属性文件
    		try{
    			if(f.exists()){	// 文件存在
    				pro.load(new FileInputStream(f)) ;	// 读取属性
    			}else{
    				pro.setProperty("apple","org.lxh.demo15.factorydemo02.Apple") ;
    				pro.setProperty("orange","org.lxh.demo15.factorydemo02.Orange") ;
    				pro.store(new FileOutputStream(f),"FRUIT CLASS") ;
    			}
    		}catch(Exception e){}
    		return pro ;
    	}
    };
    class Factory{
    	public static Fruit getInstance(String className){
    		Fruit fruit = null ;
    		try{
    			fruit = (Fruit)Class.forName(className).newInstance() ;
    		}catch(Exception e){
    			e.printStackTrace() ;
    		}
    		return fruit ;
    	}
    };
    public class FactoryDemo02{
    	public static void main(String args[]){
    		Properties pro = Init.getPro() ;
    		Fruit f = Factory.getInstance(pro.getProperty("apple")) ;
    		if(f!=null){
    			f.eat() ;
    		}
    	}
    };
    

      

      

  • 相关阅读:
    ACM的算法分类 2015-04-16 14:25 22人阅读 评论(0) 收藏
    初学Larevel 2014-08-21 11:24 90人阅读 评论(0) 收藏
    初学PHP&MySQL 2014-05-31 12:40 92人阅读 评论(0) 收藏
    codeforces 570 E. Pig and Palindromes (dp)
    codeforces 570 D. Tree Requests (dfs序)
    poj 2157 Maze (bfs)
    cf 570 C. Replacement (暴力)
    cf 570B B. Simple Game(构造)
    cf 570 A. Elections
    hdu 1429胜利大逃亡(续) (bfs+状态压缩)
  • 原文地址:https://www.cnblogs.com/wujixing/p/5430138.html
Copyright © 2011-2022 走看看