Java设计模式之抽象工厂模式

ABSTRACT FACTORY (Object Creational) 
Purpose 
Provide an interface that delegates creation calls to one or 
more concrete classes in order to deliver specific objects. 
Use When 
n The creation of objects should be independent of the system 
utilizing them. 
1 Systems should be capable of using multiple families of objects. 
2 Families of objects must be used together. 
3 Libraries must be published without exposing implementation 
details. 
4 Concrete classes should be decoupled from clients. 
Example 
Email editors will allow for editing in multiple formats including 
plain text, rich text, and HTML. Depending on the format being 
used, different objects will need to be created. If the message 
is plain text then there could be a body object that represented 
just plain text and an attachment object that simply encrypted 
the attachment into Base64. If the message is HTML then the 
body object would represent HTML encoded text and the 
attachment object would allow for inline representation and a 
standard attachment. By utilizing an abstract factory for creation 
we can then ensure that the appropriate object sets are created 
based upon the style of email that is being sent. 

Java代码 
  1. package javaPattern.abstractFactory;  
  2.   
  3. public interface AbstractFactory {  
  4.     public AbstractProduct createProductA();   
  5.     public AbstractProduct createProductB();   
  6. }  
  7. interface AbstractProduct {  
  8.     public void someMethod();  
  9. }  
  10. class ConcreteProductA implements AbstractProduct{  
  11.     public void someMethod(){  
  12.         System.out.println("具体的商品A");  
  13.     }  
  14. }  
  15. class ConcreteProductB implements AbstractProduct{  
  16.     public void someMethod(){  
  17.         System.out.println("具体的商品B");  
  18.     }  
  19. }  
  20. class ConcreteFactory implements AbstractFactory{  
  21.   
  22.     @Override  
  23.     public AbstractProduct createProductA() {  
  24.         return new ConcreteProductA();  
  25.     }  
  26.   
  27.     @Override  
  28.     public AbstractProduct createProductB() {  
  29.         return new ConcreteProductB();  
  30.     }  
  31.     public static void main(String[] args) {  
  32.         AbstractFactory abstractFactory = new ConcreteFactory();  
  33.         AbstractProduct abstractProduct = abstractFactory.createProductA();  
  34.         abstractProduct.someMethod();  
  35.     }  
  36. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值