设计模式学习(一) 工厂模式之简单工厂

设计模式学习(一) 工厂模式之简单工厂

设计模式学习(一) 工厂模式之简单工厂

Creational Pattern:

*creates objects for you rather than having you instantiate objects directly

*gives your program more flexibility in deciding which objects need to be created for a given case

 

工厂模式有以下三种形态:

简单工厂(Simple Factory)模式:又称静态工厂方法(Static Factory Method)模式

工厂方法(Factory Method)模式:又称多态性工厂(Polymorphic Factory)模式

抽象工厂(Abstract Factory)模式:又称工具箱(Kit Toolkit)模式

 

简单工厂模式其实是普通工厂模式的一个特例,今天就从这里开始吧。

其结构可以简单地表示如下:


SimpleFactory.jpg没用
Visio画,大家见谅呀


    我们从一个实际的例子来看这个简单工厂模式

假设一个农场,专门向市场销售各种水果,假设只提供良种的水果,苹果和葡萄,我们为水果设计一个抽象类Fruit,所有水果都必须实现这个接口

package  simple_Factory;
// 水果抽象出来的接口
public   interface  Fruit  {
    
void grow();
    
void harvest();
}


public   class  Apple  implements  Fruit  {

    
private int treeAge;

    
public void grow() {
        log(
"Apple is glowing");
        
    }


    
private void log(String string) {
        System.out.println(string);        
    }


    
public void harvest() {
        log(
"Apple has been harvested.");
    }

    
    
public int getTreeAge() {
        
return treeAge;
    }


    
public void setTreeAge(int treeAge) {
        
this.treeAge = treeAge;
    }


}


public   class  Grape  implements  Fruit  {

    
private boolean seedless;
    
public void grow() {
        log(
"Grape is growing------");
    }


    
    
public void harvest() {
        log(
"Grape has been harvested.");
    }

    
private void log(String string) {
        System.out.println(string);        
    }


    
public boolean isSeedless() {
        
return seedless;
    }


    
public void setSeedless(boolean seedless) {
        
this.seedless = seedless;
    }


}


public   class  OtherFruits  implements  Fruit  {

    
public void grow() {        
    }


    
public void harvest() {        
    }


}

 

FruitFactory类,水果加工厂,根据需要(不同参数代表不同的水果需求)给市场供给水果。

 

package  simple_Factory;

// 水果加工厂,根据需要给市场供给水果
public   class  FruitFactory  {
    
public static Fruit supplyFruit(String need)
    
{
        
if(need.equalsIgnoreCase("apple"))
            
return new Apple();
        
else if(need.equalsIgnoreCase("grape"))
            
return new Grape();
        
else
            
return new OtherFruits();        
    }

}

测试方法:
package  simple_Factory;

public   class  Test  {

    
/** *//**
     * 
@param args
     
*/

    
public static void main(String[] args) {
        Fruit a 
= FruitFactory.supplyFruit("apple");
        Fruit b 
= FruitFactory.supplyFruit("Grape");
        Fruit c 
= FruitFactory.supplyFruit("others");
        
        a.grow();a.harvest();
        b.grow();b.harvest();
        c.grow();c.harvest();
    }

}


    自己弄懂和讲给别人懂还是有很大差距的,第一篇文章虽然写好了,但是感觉不够好,不知道能不能给初学者一点点帮助呢……

    自强不息,继续努力!

你可能感兴趣的:(设计模式学习(一) 工厂模式之简单工厂)