静态工厂方法模式

    静态工厂方法模式中,各种产品有公共的接口,通过调用工厂类中的同一个静态方法,只要传入不同的参数,就可以得到不同的产品。

package  staticfactorymethod;

/*  水果类的接口,声明了种植、生长和收获三个方法
 * 
 
*/
public   interface  Fruit {

    
void  plant();
    
    
void  grow();
    
    
void  harvest();
    
}
package  staticfactorymethod;

public   class  Apple  implements  Fruit{

    
public   void  plant() {
        
    }
    
    
public   void  grow() {
        
    }
    
    
public   void  harvest() {
        
    }
    
}
package  staticfactorymethod;

public   class  Grape  implements  Fruit{

    
public   void  plant() {
        
    }
    
    
public   void  grow() {
        
    }
    
    
public   void  harvest() {
        
    }
    
}
package  staticfactorymethod;

public   class  Strawberry  implements  Fruit{

    
public   void  plant() {
        
    }
    
    
public   void  grow() {
        
    }
    
    
public   void  harvest() {
        
    }
    
}
package  staticfactorymethod;

public   class  FruitGardener {

    
public   static  Fruit factory (String name)  throws  BadFruitException {
        
if  (name.equalsIgnoreCase( " apple " ))
            
return   new  Apple();
        
else   if  (name.equalsIgnoreCase( " grape " ))
            
return   new  Grape();
        
else   if  (name.equalsIgnoreCase( " strawberry " ))
            
return   new  Strawberry();
        
else  
            
throw   new  BadFruitException( " no such fruit :  "   +  name);
    }
    
    
public   static   void  main(String [] args) {
        
try  {
            System.out.println(FruitGardener.factory(
" Apple " ));
            System.out.println(FruitGardener.factory(
" Grape " ));
            System.out.println(FruitGardener.factory(
" Strawberry " ));
            System.out.println(FruitGardener.factory(
" Banana " ));
        }
catch (BadFruitException bfe) {
            System.out.println(bfe);
        }
    }
}
package  staticfactorymethod;

public   class  BadFruitException  extends  Exception {

    
public  BadFruitException (String msg) {
        
super (msg);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值