Created
May 25, 2012 06:39
-
-
Save sanpingz/2786192 to your computer and use it in GitHub Desktop.
工厂方法模式
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static com.mceiba.util.Print.*; | |
import java.util.*; | |
interface Service{ | |
void method1(); | |
void method2(); | |
} | |
interface ServiceFactory{ | |
Service getService(); | |
} | |
class Implementation1 implements Service{ | |
private Implementation1() {} | |
public void method1() { println("Implementation1 method1()"); } | |
public void method2() { println("Implementation1 method2()"); } | |
public static ServiceFactory factory = | |
new ServiceFactory(){ | |
public Service getService(){ | |
return new Implementation1(); | |
} | |
}; | |
} | |
class Implementation2 implements Service{ | |
private Implementation2() {} | |
public void method1() { println("Implementation2 method1()"); } | |
public void method2() { println("Implementation2 method2()"); } | |
public static ServiceFactory factory = | |
new ServiceFactory(){ | |
public Service getService(){ | |
return new Implementation2(); | |
} | |
}; | |
} | |
public class Factories{ | |
public static void serviceConsumer(ServiceFactory fact){ | |
Service sv = fact.getService(); | |
sv.method1(); | |
sv.method2(); | |
} | |
public static void main(String[] args){ | |
serviceConsumer(Implementation1.factory); | |
serviceConsumer(Implementation2.factory); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment