工厂方法模式

操作接口:

package com.jerry.design.factoryMethod.imp;


/**

 * 

 * @author jerry

 *

 */

public interface interfaceTest {

public void test(String name);


}


实现类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);

}


}

实现类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();

}


}


子类B:

package com.jerry.design.factoryMethod.impl;

import com.jerry.design.factoryMethod.imp.abstractClass;

import com.jerry.design.factoryMethod.imp.interfaceTest;

public class ClassB extends abstractClass {

@Override
public interfaceTest getImpl() {
return new ImplB();
}

}

测试类:

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

}

}


总结:分离出业务与创建,延迟实现。

posted on 2012-02-19 21:53 疯狂的蜗牛 阅读(60) 评论(0)  编辑  收藏 所属分类: 设计模式


只有注册用户登录后才能发表评论。


网站导航:
 
<2024年11月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

导航

统计

公告

@import url(http://www.blogjava.net/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);

常用链接

留言簿

随笔档案

文章分类

文章档案

搜索

最新评论