Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

Java设计模式之工厂方法模式

$
0
0

1,工厂方法模式(每个具体角色由其具体工厂产生),

①,抽象角色

②,具体角色

③,抽象工厂

④,具体工厂

抽象工厂模式(与工厂模式区别在于创建对象的复杂程度上)

①,抽象角色:

package method.factory;
public interface AbstractMove {
public void run();
}

②,具体角色

package method.factory;
public class Bus implements AbstractMove {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("This is a Bus running");
}
}

package method.factory;
public class Plan implements AbstractMove {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("This is Plan running");
}
}

③,抽象工厂

package method.factory;
public abstract class AbstractFactory {
abstract AbstractMove create();
}

④,具体工厂

package method.factory;
public class BusFactory extends AbstractFactory {
@Override
AbstractMove create() {
// TODO Auto-generated method stub
return new Bus();
}
}

package method.factory;
public class PlanFactory extends AbstractFactory {
@Override
AbstractMove create() {
// TODO Auto-generated method stub
return new Plan();
}
}

Test:

package method.factory;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
AbstractFactory af = new PlanFactory();
AbstractMove move = af.create();
move.run();

AbstractFactory af1 = new BusFactory();
AbstractMove move1 = af1.create();
move1.run();
}
}

result:

This is Plan running
This is a Bus running


作者:luyee2010 发表于2013-3-26 0:43:47 原文链接
阅读:114 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>