java开发模式-简单工厂模式

来源:互联网 发布:手机开淘宝店流程步骤 编辑:程序博客网 时间:2024/05/17 02:10

1、 简单工厂模式

优点

         使用简单工厂使得客户端和业务层有效的被隔离开,由工厂来根据客户端的请求来创建适合的业务对象,让后在返回给客户端。客户端不知道业务对象是如何被创建的而业务层也不知道客户端的存在,也就是说对于客户端来说业务对象是透明的,而对于业务层客户端同样也是透明的,这样就实现的客户端和业务层的解耦合。

缺点

 因为所有的业务对象的实例化逻辑都是由这个简单工厂实现,也就是说这个工厂类集中了所有的产品创建逻辑,形成了一个无所不知的全能类,也称之为 God Class,当业务对象层次很复杂时这个工厂存在大量的判断逻辑,对系统的扩展和文档性带来了负面的影响。

每增加一个具体产品时 ,就要修改工厂方法,工厂方法负责了所有具体产品的创建。

 

例:

葡萄 Grape

苹果 Apple

 

public interface Fruit {

    void grow();

    void harvest();

    void plant();

}

//苹果

public class Apple implements Fruit {

    private int treeAge;

    public void grow() {    

       System.out.println("Apple is growing...");

    }

    public void harvest() {

       System.out.println("Apple has been harvested.");

    }

    public void plant() {

       System.out.println("Apple has been planted.");

    }

    public int getTreeAge() {

       return treeAge;

    }

    public void setTreeAge(int treeAge) {

       this.treeAge = treeAge;

    }

}

 

 

//葡萄

public class Grape implements Fruit {

     private boolean seedless; 

     public boolean isSeedless() {

        return seedless;

     }

     public void setSeedless(boolean seedless) {

        this.seedless = seedless;

     }

     public void grow() {

        System.out.println("Grape is growing...");

     }

     public void harvest() {

        System.out.println("Grape has been harvested.");

     }

     public void plant() {

        System.out.println("Grape has been planted.");   

     } 

}

 

 

// 静态工厂方法

 

public class FruitGardener {

public static Fruit factory(String which)throws BadFruitException {

       if (which.equalsIgnoreCase("apple")) {

           return new Apple();     

       } else if (which.equalsIgnoreCase("grape")) {

           return new Grape();

       } else {

           throw new BadFruitException("Bad fruit request");

       }

    }

}

 

//异常处理

public class BadFruitException extends Exception {

    public BadFruitException(String msg) {

       super(msg);

    }

}

 

 

 

public class Client {

    public static void main(String[] args) {

       try {

           Fruit apple = (Fruit) FruitGardener.factory("Apple");

System.out.println("apple is class: " + apple.getClass().getName());

           apple.plant();

           apple.grow();

           apple.harvest();

           System.out.println();

 

           Fruit grape = (Fruit) FruitGardener.factory("grape");

System.out.println("grape is class: " + grape.getClass().getName());

           grape.plant();

           grape.grow();

           grape.harvest();

 

       } catch (BadFruitException e) {

           e.printStackTrace();

       }

    }

}

 

运行结果:

 

apple is class: factory.Apple

Apple has been planted.

Apple is growing...

Apple has been harvested.

 

grape is class: factory.Grape

Grape has been planted.

Grape is growing...

Grape has been harvested.

原创粉丝点击