当前位置:编程学习 > JAVA >>

设计模式DP--抽象工厂

设计模式DP(3)抽象工厂
特点:系统独立于产品类的创建、组合与使用
            对外提供相应的接口,而并非实现类
           系统由多个不同系统的产品当中的一个来配置 
           考虑不同产品类之间的关联性
           对工厂方法的一个提升(不同的工厂,创建不同产品的实例)
代码:
##最顶级抽象工厂类,创建抽象
public interface IAbstractFactory{
           ICat createCat();
           IDog createDog();
}
##下面定义两种具体动物工厂 (BlackAnimalFactory 与WhiteAnimalFactory)
public class BlackAnimalFactory  implements IAbstractFactory{
        public   ICat createCat(){
              return new BlackCat();
       }
        public   IDog createDog(){
              return new BlackDog();
        }
}
public class WhiteAnimalFactory  implements IAbstractFactory{
        public   ICat createCat(){
              return new WhiteCat();
       }
        public   IDog createDog(){
              return new WhiteDog();
        }
}
##定义产品类接口,在这里是猫与狗接口
public interface ICat{
      void eat();
}
public interface IDog{
      void eat();
}
###定义产品类接口 不同形态(黑白)的具体实现,在这里是黑猫、黑狗与白猫、白狗
public class BlackCat implements Cat{
   public eat(){
       System.out.println("  the black cat is eatting !!");
   }
}
public class BlackDog implements Dog{
   public eat(){
       System.out.println("  the black dog is eatting !!");
   }
}
public class WhiteCat implements Cat{
   public eat(){
       System.out.println("  the white cat is eatting !!");
   }
}
public class WhiteDog implements Dog{
   public eat(){
       System.out.println("  the white dog is eatting !!");
   }
}
调用:
public static void main(String arg[]){
        IFactory if1 = new BlackAnimalFactory();
        ICat ic1 = if1.createCat();
        ic1.eat();
        IDog id1 = if1.createDog();
        id1.eat();
 
       IFactory if2 = new WhiteAnimalFactory();
        ICat ic2 = if2.createCat();
        ic2.eat();
        IDog id2 = if2.createDog();
        id2.eat();
}
结果:
the black cat is eatting !!
the black dog is eatting !!
the white cat is eatting !!
the white dog is eatting !!
补充:软件开发 , Java ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,