首页 > 其他 > 详细

工厂模式PK 工厂变种模式

时间:2016-03-08 02:22:13      阅读:169      评论:0      收藏:0      [点我收藏+]

// 产品接口 ? ? ? ??

public interface Product { ??

? ? public void getName(); ??

} ??

??

// 具体产品A ??

public class ProductA implements Product { ??

? ? public void getName() { ??

? ? ? ? System.out.println(" ?I am ProductA ?"); ??

? ? } ??

} ??

??

// 具体产品B ??

public class ProductB implements Product { ??

? ? public void getName() { ??

? ? ? ? System.out.println(" ?I am ProductB ?"); ??

? ? } ??

} ??

??

// 工厂类 ??

public class ProductCreator { ??

? ? public Product createProduct(String type) { ??

? ? ? ? if (" A ".equals(type)) { ??

? ? ? ? ? ? return new ProductA(); ??

? ? ? ? } ??

? ? ? ? if (" B ".equals(type)) { ??

? ? ? ? ? ? return new ProductB(); ??

? ? ? ? } else ?

? ? ? ? ? ? return null; ??

? ? } ??

? ? public static void main(String[] args) { ??

? ? ? ? ProductCreator creator = new ProductCreator(); ??

? ? ? ? creator.createProduct(" A ").getName(); ??

? ? ? ? creator.createProduct(" B ").getName(); ??

? ? } ??

} ?

?

--------------------------------另一种设计模式-----------------------------------

// 产品接口 ? 具体产品A ??具体产品B ? 不变,仅仅改变工厂实现,就是一种新模式,小伙伴知道这是一种什么模式吗?

//工厂类 ??

public class ProductCreator { ??

?

public void createProduct(Product p) {?

p.getName();

System.out.println("------ProductCreator------p.getName");

}?

}

?

public static void main(String[] args) { ??

? ? ? ? ProductCreator creator = new ProductCreator(); ??

? ? ? ? creator.createProduct(new ProductA());

? ? ? ? ?creator.createProduct(new ProductB());

? ? } ??

?

工厂模式PK 工厂变种模式

原文:http://gaojingsong.iteye.com/blog/2281168

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!