Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1895745
  • 博文数量: 606
  • 博客积分: 9991
  • 博客等级: 中将
  • 技术积分: 5725
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-17 19:07
文章分类

全部博文(606)

文章存档

2011年(10)

2010年(67)

2009年(155)

2008年(386)

分类:

2008-07-30 22:21:34

在我们学习spring之前了解工厂模式的使用,对我们学习spring,特别是依赖注入的理解有很好的作用。工厂模式就是负责将大量有共同接口的类实例化,而不必事先知道每次是实例化哪一个类的模式。而后面用到的spring则相当于一个大工厂。

       现在假设我们想要种水果,包括苹果,橙子,雪梨。

       我们可以先设计一个接口Fruit:

public interface Fruit {

    String name = null;

    void grow();

    void harvest();

}

里面包含了种植,收获这两个方法的声明。

现在我要实现这个接口:

public class Apple implements Fruit{

    String name;

    public Apple() {

    }

    public Apple(String name){

        this.name = name;

    }

    public void grow(){

        System.out.println("Grow apple!");

    }

    public void harvest(){

        System.out.println("Harvest apple!");

    }

}

其它两种水果也一样。

现在写一个水果的异常类,用于生产水果发生异常时的处理:

public class BadFruitException extends Exception{

    public BadFruitException(){

    }

    public BadFruitException(String msg){

        super(msg);

    }

}

好了,现在开始写水果的工厂类:

public class FruitFactory {

    public FruitFactory() {

    }

    public static Fruit factory(String name) throws BadFruitException{

        if(name.equalsIgnoreCase("apple"))

           return new Apple();

        else if(name.equalsIgnoreCase("orange"))

           return new Orange();

       

        else if(name.equalsIgnoreCase("pear"))

           return new Pear();

       

        else

            throw new BadFruitException("Bad fruit name!");

    }

}

这个工厂类很简单,就是根据我们输入的水果名,返回这种水果的实例。如果工厂没有这种水果,则抛出一个BadFruitException,在调用Fruit.factory()的方法体里面捕获。

OK,接下来写主方法:

    public static void main(String[] args) {

        Fruit fruit = null;

        try {

            fruit = FruitFactory.factory("apple");

            fruit.grow();

            fruit.harvest();

            fruit = FruitFactory.factory("orange");

            fruit.grow();

            fruit.harvest();           

            fruit = FruitFactory.factory("pear");

            fruit.grow();

            fruit.harvest();

        } catch (BadFruitException ex) {

            ex.printStackTrace();

        }

}

我们可以看到,主要我们输入不同的水果名,就可以获取到该水果的一个实例,我们只需要引用一个接口就可以了,这样做大大降低了程序之间的耦合度。

而我们最后将程序打包给使用者使用时,也只需暴露接口,而不必将里面的细节公开。而使用者只需告诉工厂我想使用哪种水果就可以了。

好了,简单的工厂模式就介绍到这里吧。

 

 

http://hi.baidu.com/coolcat_police/blog/item/35a05dcafd851882c8176875.html

 

阅读(754) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~