接口类:
package com.jerry.design.abstractFactory.imp; public interface DoAJob { public void doSometingLikeA(); }
package com.jerry.design.abstractFactory.imp; public interface DoBJob { public void doSometingLikeB(); }
package com.jerry.design.abstractFactory.imp; public interface AbstractFactory { public DoAJob createA(); public DoBJob createB(); }
实现类:
package com.jerry.design.abstractFactory.impl; import com.jerry.design.abstractFactory.imp.DoAJob; public class DoA implements DoAJob { @Override public void doSometingLikeA() { System.out.println(" do something like a!"); } }package com.jerry.design.abstractFactory.impl; import com.jerry.design.abstractFactory.imp.DoBJob; public class DoB implements DoBJob { @Override public void doSometingLikeB() { System.out.println(" do something like b!"); } }
package com.jerry.design.abstractFactory.impl; import com.jerry.design.abstractFactory.imp.AbstractFactory; import com.jerry.design.abstractFactory.imp.DoAJob; import com.jerry.design.abstractFactory.imp.DoBJob; public class Factory implements AbstractFactory { @Override public DoAJob createA() { return new DoA(); } @Override public DoBJob createB() { return new DoB(); } }
测试类:
package com.jerry.design.abstractFactory.client; import com.jerry.design.abstractFactory.imp.AbstractFactory; import com.jerry.design.abstractFactory.impl.Factory; import com.jerry.design.factoryMethod.imp.abstractClass; import com.jerry.design.factoryMethod.impl.ClassA; import com.jerry.design.factoryMethod.impl.ClassB; public class Test{ public static void main(String[] args) { AbstractFactory ac = new Factory(); ac.createA().doSometingLikeA(); ac.createB().doSometingLikeB(); // do something like a! // do something like b! } }
总结:选择一类实现的子类 例如我们可以继续扩展DoA的接口,使其复杂,那么就可以有多个子类实现这个接口,可是对于调用者来说,使看不到的,这也正是面向接口编程的优点。