zoukankan      html  css  js  c++  java
  • Java学习笔记——Java工厂模式之简单工厂

    package com.app;
    import java.util.Date;
    
    
    /*
     * 工厂模式:简单工厂、工厂方法、抽象工厂
     * 
     * */
    public class  Test0718_Factory {
    	public static void main(String[] args) {
    		Fruit.FruitJudge(new Date());
    		Fruit.FruitJudge(5);
    		Fruit.FruitJudge(new Fruit());
    		Fruit.FruitJudge(new Cherry());
    		Fruit.FruitJudge(new Apple());
    		System.out.println();
    		
    		Fruit fruit1 = Fruit.getFruit(1);
    		Fruit fruit2 = Fruit.getFruit(2);
    		
    		fruit1.grow();
    		fruit2.grow();
    		((Apple)fruit2).m1();
    	}
    }
    class Fruit {
    	public void grow(){
    		System.out.println("水果在生长");
    	}
    
    
    	public static void FruitJudge(Object obj){
    		if(! (obj instanceof Fruit)){
    			System.out.println("参数类型不兼容");
    		}  else {
    			if(obj instanceof Cherry){
    				Cherry f = (Cherry)obj;//造型,高->低
    				f.grow();
    			} else if(obj instanceof Apple){
    				Apple f = (Apple)obj;
    				f.grow();
    				f.m1();//强转后,可以明确调用子类新加的成员
    			} else {
    				Fruit f = (Fruit)obj;
    				f.grow();
    			}
    		}
    	}
    
    
    	//简单工厂模式,根据值的不同返回不同的子类实例
    	public static Fruit getFruit(int code){
    		Fruit obj = null;
    		if(code==1) {
    			obj = new Cherry();
    		} else if(code==2) {
    			obj = new Apple();
    		} else {
    			obj = new Fruit();
    		}
    		return obj;
    	}
    }
    class Cherry extends Fruit {
    	public void grow(){
    		System.out.println("樱桃在生长");
    	}
    }
    class Apple extends Fruit {
    	public void grow(){
    		System.out.println("苹果在生长");
    	}
    	public void m1(){ 
    		System.out.println("苹果的m1"); 
    	}
    }

    执行结果:

    ---------- 运行 ----------
    参数类型不兼容
    参数类型不兼容
    水果在生长
    樱桃在生长
    苹果在生长
    苹果的m1


    樱桃在生长
    苹果在生长
    苹果的m1


    输出完成 (耗时 0 秒) - 正常终止

  • 相关阅读:
    左孩子右兄弟的字典树
    UVA 1401 Remember the Word
    HDOJ 4770 Lights Against Dudely
    UvaLA 3938 "Ray, Pass me the dishes!"
    UVA
    Codeforces 215A A.Sereja and Coat Rack
    Codeforces 215B B.Sereja and Suffixes
    HDU 4788 Hard Disk Drive
    HDU 2095 find your present (2)
    图的连通性问题—学习笔记
  • 原文地址:https://www.cnblogs.com/java20130723/p/3211374.html
Copyright © 2011-2022 走看看