2008-06-17

工厂模式

简单工厂模式

// 产品接口          
public interface Product {    
   
    public void getName();    
   
}    
   
// 具体产品A    
public class ProductA implements Product {    
   
    public void getName() {    
        System.out.println("  I am ProductA  ");    
    }    
   
}    
   
// 具体产品B    
public class ProductB implements Product {    
   
    public void getName() {    
        System.out.println("  I am ProductB  ");    
    }    
   
}    
   
// 工厂类    
public class ProductCreator {    
   
    public Product createProduct(String type) {    
        if (" A ".equals(type)) {    
            return new ProductA();    
        }    
        if (" B ".equals(type)) {    
            return new ProductB();    
        } else   
            return null;    
    }    
   
    public static void main(String[] args) {    
        ProductCreator creator = new ProductCreator();    
        creator.createProduct(" A ").getName();    
        creator.createProduct(" B ").getName();    
    }    
}  




工厂方法模式
public interface Factory 
{ 
Apple createApple(); 
} 

public class ConcreteFactory1 implements Factory 
{ 
public Apple createApple() 
{ 
return new RedApple(); 
} 

} 

public class ConcreteFactory2 implements Factory 
{ 
public Apple createApple() 
{ 
return new GreenApple(); 
} 
} 



抽象工厂模式
public interface Factory 
{ 
Apple createApple(); 
Grape createGrape(); 
} 

public class ConcreteFactory1 implements Factory 
{ 
public Apple createApple() 
{ 
return new RedApple(); 
} 

public Grape createGrape() 
{ 
return new RedGrape(); 
} 

} 

public class ConcreteFactory2 implements Factory 
{ 
public Apple createApple() 
{ 
return new GreenApple(); 
} 

public Grape createGrape() 
{ 
return new GreenGrape(); 
} 

}

评论
发表评论

您还没有登录,请登录后发表评论

congpeixue
搜索本博客
存档
最新评论