抽象工厂模式学习
抽象在厂模式用文字语言讲呢,没有意思,听了半天也没有什么意思..也学不进去,,
那么我就做一个例子来..讲解抽象工厂模式::
????? 有一个产品接口
package com.newer.abstractfactory;
public interface Product {
// 有一个无实现的方法
??? public void f();
}
然后有两个厂商 一个是IBM 一个是DELL
?
//Dell
package com.newer.abstractfactory;
public class DellProduct implements Product {
?public void f() {
??// TODO Auto-generated method stub
???????????? System.out.println("dellProduct f()...........");
?}
}
//IBM
public class IBMProduct implements Product {
?public void f() {
??// TODO Auto-generated method stub
?? System.out.println("IBMProduct f()...........");
?}
}
package com.newer.abstractfactory;
搞一个抽象工厂...这个工厂有两个作用.生产产品的,和生产工厂的
package com.newer.abstractfactory;
public abstract class AbstractFactory {
?private static String productName = "IBMProduct";
?public static AbstractFactory getInstance() {
??AbstractFactory af = null;
??try {
//?反射?? 搞的 类名用到了字符串,,有字符串这就己为着可以从配置中读出来.这就解出了.产品工厂.和抽象工厂 各自这间的的偶和.
???af = (AbstractFactory)Thread.currentThread().getContextClassLoader().loadClass(productName).newInstance();
??} catch (Exception e) {
???// TODO: handle exception
???e.printStackTrace();
??}
??return af;
?}
?public abstract Product createProduct();
?public static String getProductName() {
??return AbstractFactory.productName;
?}
?public static void setProductName(String productName) {
??AbstractFactory.productName = productName;
?}
}
//然后就是两个产品的工厂类
//dell? IBm
package com.newer.abstractfactory;
public class DellProductFactory extends AbstractFactory{
????? public Product createProduct(){
??? ?? return new DellProduct();
????? }
}
package com.newer.abstractfactory;
public class IBMProductFactory extends AbstractFactory{
?????? public Product createProduct(){
??? ??? return new IBMProduct();
?????? }
}
?
以上两个工厂类是生产各自的产品......完全体现解除偶和
?
现在就是差一个客户端程序员来用这个抽象工厂了
?
package com.newer.abstractfactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
public class Test {
?/**
? * @param args
? */
?public static void main(String[] args)throws Exception {
??// TODO Auto-generated method stub
???????? try {
??????? ? File file = new File("src/com/newer/abstractfactory/product.properties");
??????? ? InputStream is = new FileInputStream(file);
??????? ?
??????? ?System.out.println(is);
???Properties prop = new Properties();
???prop.load(is);
???String factoryName = prop.getProperty("product");
???System.out.println("factory:::"+factoryName);
???AbstractFactory.setProductName(factoryName);
???
???AbstractFactory af = AbstractFactory.getInstance();
???Product p = af.createProduct();
???p.f();
??} catch (Exception e) {
???// TODO: handle exception
???e.printStackTrace();
??}
?}
}
?
?
还有一个java属性文件的内容product.properties
?product=com.newer.abstractfactory.IBMProductFactory
现在就可以看效果了..现在我生产产品,,就解除了偶和..生产什么产品,,都不用改代码了.只要改配置文件就可以了.
只要配置文件一改,产品就换了.不动其它的代码..
有可能我说的不够好...大家多提一点意见啊,
请一下啊
?
?