工厂方法模式:就是定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类当中。核心工厂类不在负责产品的创建,这样核心类成为一个抽象工厂角色,仅负责具体工厂子类必须实现的接口,这样进一步抽象化的好处是 使得工厂方法模式可以使系统在不修改具体工厂角色的情况下引进新的产品。
interface Service{
void methodOne();
void methodTwo();
}
interface ServiceFactory{
Service getService();
}
class ImplementationOne implements Service{
ImplementationOne(){};
public void methodOne(){
System.out.println("ImplementationOne's methodOne()");
}
public void methodTwo() {
System.out.println("ImplementationOne's methodTwo()");
}
}
class ImplementationTwo implements Service{
ImplementationTwo(){}
public void methodOne() {
System.out.println("ImplementationTwo's methodOne()");
}
public void methodTwo() {
System.out.println("ImplementationTwo's methodTwo()");
}
}
class ImplementationOneFactory implements ServiceFactory{
@Override
public Service getService() {
return new ImplementationOne();
}
}
class ImplementationTwoFactory implements ServiceFactory{
@Override
public Service getService() {
return new ImplementationTwo();
}
}
public class FactoryMethodDemo {
public static void serviceConsumer(ServiceFactory sFact){
Service svc = sFact.getService();
svc.methodOne();
svc.methodTwo();
}
public static void main(String[] args){
serviceConsumer(new ImplementationOneFactory());
serviceConsumer(new ImplementationTwoFactory());
}
}
/output/
ImplementationOne’s methodOne()
ImplementationOne’s methodTwo()
ImplementationTwo’s methodOne()
ImplementationTwo’s methodTwo()
这个代码的结构,也可以使用匿名内部类来实现:
interface Service{
void methodOne();
void methodTwo();
}
interface ServiceFactory{
Service getService();
}
class ImplementationOne implements Service{
@Override
public void methodOne() {
System.out.println("ImplementationOne methodOne()");
}
@Override
public void methodTwo() {
System.out.println("ImplementationOne methodTwo()");
}
public static ServiceFactory factory=
new ServiceFactory(){
public Service getService(){
return new ImplementationOne();
}
};
}
class ImplementationTwo implements Service{
@Override
public void methodOne() {
System.out.println("ImplementationTwo methodOne()");
}
@Override
public void methodTwo() {
System.out.println("ImplementationTwo methodTwo()");
}
public static ServiceFactory factory=
new ServiceFactory(){
public Service getService(){
return new ImplementationTwo();
}
};
}
public class AnonumousInnerClassDemo {
public static void serviceConsumer(ServiceFactory fact){
Service service=fact.getService();
service.methodOne();
service.methodTwo();
}
public static void main(String[] args){
serviceConsumer(ImplementationOne.factory);
serviceConsumer(ImplementationTwo.factory);
}
}
/output/
ImplementationOne methodOne()
ImplementationOne methodTwo()
ImplementationTwo methodOne()
ImplementationTwo methodTwo()