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