設(shè)計(jì)模式之工廠模式:
1、 掌握什么叫反射
2、 掌握class類(lèi)的作用
3、 通過(guò)反射實(shí)例化對(duì)象
4、 通過(guò)反射調(diào)用類(lèi)中方法的操作原理
5、 工廠設(shè)計(jì)的改進(jìn),重點(diǎn)掌握其思想,程序和配置相分離
package fac.cn;
interface Fruit{
public void eat();
}
class Apple implements Fruit{
public void eat(){
System.out.println("吃蘋(píng)果");
}
}
class Orange implements Fruit{
public void eat(){
System.out.println("吃橘子");
}
}
class Factory{
public static Fruit getInstance(String className){
Fruit f=null;
if(className.equals("Apple"))
f=new Apple();
else if(className.equals("Orange"))
f=new Orange();
return f;
}
}
public class FactoryDemo {
public static void main(String args[]){
Fruit fruit=Factory.getInstance("Apple");
fruit.eat();
}
}
注:本程序的確實(shí)現(xiàn)了工廠操作。所有的問(wèn)題集中在工廠操作中,因?yàn)槊看沃灰辉黾幼宇?lèi),則必須修改工廠。此時(shí)可以根據(jù)反射機(jī)制來(lái)完成,通過(guò)Class類(lèi)來(lái)修改工廠
如下表即為修改的工廠類(lèi)和主類(lèi)
class Factory{
public static Fruit getInstance(String className){
Fruit f=null;
try {
f=(Fruit)Class.forName(className).newInstance();
}
catch (Exception e) {
e.printStackTrace();
}
return f;
}
}
public class FactoryDemo2 {
public static void main(String args[]){
Fruit fruit=Factory.getInstance("fac2.cn.Apple");
fruit.eat();
}
}
注:在以上操作中,工廠類(lèi)完全不用修改,但是每次操作應(yīng)用時(shí),都必須輸入很長(zhǎng)的包.類(lèi).名稱(chēng),使用時(shí)很不方便。最好的方法是通過(guò)一個(gè)別名來(lái)表示這個(gè)完成的包.類(lèi)名稱(chēng),而且在類(lèi)增加的時(shí)候,別名也可以自動(dòng)增加。所以如果想要完成這樣的操作,可以使用屬性類(lèi)配置
class MyPropertiesOperate{//屬性操作類(lèi)
private Properties pro=null;
private File file=new File("D:\\Workplace"+File.separator+"Fruit.properties");
public MyPropertiesOperate(){
this.pro=new Properties();
if(file.exists()){//文件存在
try {
pro.loadFromXML(new FileInputStream(file)); //讀取
}
catch (Exception e) {
}
}
else this.save();
}
private void save(){
this.pro.setProperty("Apple", "cn3.Apple");
this.pro.setProperty("Orange", "cn3.Orange");
try {
this.pro.storeToXML(new FileOutputStream(this.file),"Fruit"); //讀取
}
catch (Exception e) {
}
}
public Properties getProperties(){
return this.pro;
}
}
public class FactoryDemo3 {
public static void main(String args[]){
Properties myPro=new MyPropertiesOperate().getProperties();
Fruit fruit=Factory.getInstance(myPro.getProperty("Orange"));
fruit.eat();
}
}
注:從以上的操作代碼中發(fā)現(xiàn),程序通過(guò)一個(gè)配置文件,可以控制程序的執(zhí)行,也就是達(dá)到了配置文件和程序相分離的目的。這個(gè)設(shè)計(jì)思想現(xiàn)在還在使用中,包括三大框架等。最新的設(shè)計(jì)理論,是將注釋寫(xiě)入代碼之中,讓注釋起到程序控制的作用。要實(shí)現(xiàn)此操作,則使用Annotation完成
posted on 2012-06-28 16:47
兔小翊 閱讀(108)
評(píng)論(0) 編輯 收藏