这个desgin pattern 的意思是factory of factories, 不同于factory pattern, 根据用户的input 来new 不同的对象,这里是直接new 不同的factory。然后让不同的工厂来负责生产不同的对象。
我觉得已经有让人找不到干活的代码到底在哪里的意思了。
Usage in JDK:
javax.xml.parsers.DocumentBuilderFactory #newInstance()
javax.xml.transform.TransformerFactory #newInstance()
javax.xml.xpath.XPathFactory #newInstance()
-
package abstractfactory;
-
-
interface IMobile{
-
public void cost();
-
public void pictureCapacity();
-
public void batterPower();
-
}
-
-
class Lenovo implements IMobile{
-
-
@Override
-
public void cost(){
-
System.out.println("Lenovo Cost starts from 10000");
-
}
-
-
@Override
-
public void pictureCapacity(){
-
System.out.println("Lenovo camera capacity starts from 10MP");
-
-
}
-
-
@Override
-
public void batterPower(){
-
System.out.println("Lenovo battery power starts from 2500 MAH");
-
}
-
-
@Override
-
public String toString(){
-
return "Lenovo [toString()= " +super.toString() +" ]";
-
}
-
}
-
-
class Samsung implements IMobile{
-
-
@Override
-
public void cost(){
-
System.out.println("Samsung Cost starts from 6000");
-
}
-
-
@Override
-
public void pictureCapacity(){
-
System.out.println("Samsung camera capacity starts from 4MP");
-
-
}
-
-
@Override
-
public void batterPower(){
-
System.out.println("Samsung battery power starts from 1200 MAH");
-
}
-
-
}
-
-
interface IMobileFactory{
-
public IMobileFactory createMobile(String type);
-
}
-
-
class MobileFactory implements IMobileFactory{
-
-
@Override
-
public IMobileFactory createMobile(String type){
-
IMobileFactory obj = null;
-
if("lenf".equalsIgnoreCase(type)){
-
obj = new LenovoMobileFactory();
-
}else if("samf".equalsIgnoreCase(type)){
-
obj = new SamsungMobileFactory();
-
}
-
return obj;
-
}
-
}
-
-
class LenovoMobileFactory extends MobileFactory{
-
Lenovo createLenovoMobile(){
-
return new Lenovo();
-
}
-
}
-
-
class SamsungMobileFactory extends MobileFactory{
-
Samsung createMobileFactory(){
-
return new Samsung();
-
}
-
}
-
-
public class AbstractFactoryDemo {
-
public static void main(String[] args){
-
MobileFactory factory = new MobileFactory();
-
LenovoMobileFactory lmf = (LenovoMobileFactory)factory.createMobile("lenf");
-
Lenovo ln = (Lenovo)lmf.createLenovoMobile();
-
ln.batterPower();
-
ln.pictureCapacity();
-
}
-
}
阅读(530) | 评论(0) | 转发(0) |