简单工厂模式

来源:互联网 发布:api原油数据分析 编辑:程序博客网 时间:2024/06/06 11:32

/**  * @function  * @version 2015年1月29日 下午7:30:12 */public class Main {public static void main(String[]args){try {//直接跟工厂要一个苹果,工厂就给你造一个苹果Fruit apple = FruitFactory.createFruit("apple");apple.getSelf();//查看下水果都有的属性} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}/** * 模拟产品特性 * 水果 * @author tj * */interface Fruit{void getSelf();//模拟个产品的特性,例如获取自身的名字}/** * 水果工厂 * @author tj * */class FruitFactory{//生产水果的方法public static Fruit createFruit(String fruit) throws Exception{if(fruit.equalsIgnoreCase("apple"))return new Apple();else if(fruit.equalsIgnoreCase("pear"))return new Pear();else throw new Exception();}}//实例水果,class Pear implements Fruit{@Overridepublic void getSelf() {// TODO Auto-generated method stubSystem.out.println(this.getClass().getName());}}//实例水果class Apple implements Fruit{@Overridepublic void getSelf() {System.out.println(this.getClass().getName());}}

考虑设计模式的之前

应该先考虑简单工厂模式能解决什么问题

毕竟应该是先有问题 后有解决方案 然后就是出现简单工厂模式这种设计模式

简单工厂模式能解决的问题 目前理解是 可以将类的实例化延迟 

贴代码


0 0
原创粉丝点击