1.建立配置文件pet.properties
dog=demo04.Dog
cat=demo04.Cat
pig=demo04.Pig
2.建立相关类 pet.java
[代码]java代码:
1
2
3
4
5
6
7
8
|
package demo04; public abstract class Pet { //抽象宠物类 } class Dog extends Pet{} //Dog类 class Cat extends Pet{} //Cat类 class Pig extends Pet{} //Pig类 |
3.建立宠物工厂类PetFactory.java
[代码]java代码:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
package demo04; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; public class PetFactory { public static Pet getPet(String tag){ Properties p= new Properties(); //声明properties对象 try { p.load( new FileInputStream( "pet.properties" )); //加载配置文件 } catch (Exception e) { e.printStackTrace(); } Pet pet= null ; try { Class<!--?-->cla=Class.forName(p.getProperty(tag)); //利用反射获取对象类 Object obj=cla.newInstance(); //生成实例 pet=(Pet)obj; //强制类型转换 } catch (Exception e) { e.printStackTrace(); } return pet; } } |
4.测试类
[代码]java代码:
01
02
03
04
05
06
07
08
09
10
11
12
|
package demo04; public class Test { public static void main(String[] args) { Pet pet=PetFactory.getPet( "dog" ); System.out.println(pet); } } |