工廠方法模式
操作接口:package com.jerry.design.factoryMethod.imp;
/**
*
* @author jerry
*
*/
public interface interfaceTest {
public void test(String name);
}
實現(xiàn)類A:
package com.jerry.design.factoryMethod.impl;
import com.jerry.design.factoryMethod.imp.interfaceTest;
/**
*
* @author jerry
*
*/
public class ImplA implements interfaceTest {
public void test(String name){
System.out.println(" my ImplA name is:"+name);
}
}
實現(xiàn)類B:
package com.jerry.design.factoryMethod.impl;
import com.jerry.design.factoryMethod.imp.interfaceTest;
/**
*
* @author jerry
*
*/
public class ImplB implements interfaceTest {
public void test(String name){
System.out.println(" my ImplB name is:"+name);
}
}
抽象類:
package com.jerry.design.factoryMethod.imp;
public abstract class abstractClass {
public void test(String name){
interfaceTest impl = getImpl();
impl.test(name);
}
public abstract interfaceTest getImpl() ;
}
子類A;
package com.jerry.design.factoryMethod.impl;
import com.jerry.design.factoryMethod.imp.abstractClass;
import com.jerry.design.factoryMethod.imp.interfaceTest;
public class ClassA extends abstractClass {
@Override
public interfaceTest getImpl() {
return new ImplA();
}
}
package com.jerry.design.factoryMethod.client;
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) {
abstractClass ac = new ClassA();
ac.test("yushh");
abstractClass ac2 = new ClassB();
ac2.test("yushh2");
// my ImplA name is:yushh
// my ImplB name is:yushh2
}
}
總結:分離出業(yè)務與創(chuàng)建,延遲實現(xiàn)。
posted on 2012-02-19 21:53 瘋狂的蝸牛 閱讀(63) 評論(0) 編輯 收藏 所屬分類: 設計模式