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 秒) - 正常终止

  • 相关阅读:
    html中的块级元素、行内元素
    ptyhon_opencv 图像的基本操作
    正则表达式总结 2017.1.6
    HashMap 中的 entrySet()使用方法 2016.12.28
    (转)Redis持久化的几种方式
    负数与二进制换转方法
    (转)2019JAVA面试题附答案(长期更新)
    Java后端技术面试汇总(第一套)
    (转)Dubbo服务暴露过程源码分析
    Dubbo消费方服务调用过程源码分析
  • 原文地址:https://www.cnblogs.com/java20130723/p/3211374.html
Copyright © 2011-2022 走看看