接口的工厂模式实现

    1. interface Service{
    2. void method1();
    3. void method2();
    4. }
    5. interface ServiceFactory{
    6. Service service();
    7. }
    8. public class Factories {
    9. public static void consumeFactories(ServiceFactory serviceFactory){
    10. //可以加一些逻辑处理,将变化的部分交给实现类进行处理
    11. Service service = serviceFactory.service();
    12. service.method1();
    13. service.method2();
    14. }
    15. public static void main(String[] args) {
    16. consumeFactories(new ServiceFactoryImpl2());
    17. }
    18. }
    19. class ServiceImpl1 implements Service{
    20. public void method1() { System.out.println("ServiceImpl1 method1 ");}
    21. public void method2() { System.out.println("ServiceImpl1 method2 ");}
    22. }
    23. class ServiceFactoryImpl1 implements ServiceFactory{
    24. public Service service() {
    25. return new ServiceImpl1();
    26. }
    27. }
    28. class ServiceImpl2 implements Service{
    29. public void method1() { System.out.println("ServiceImpl2 method1 ");}
    30. public void method2() { System.out.println("ServiceImpl2 method2 ");}
    31. }
    32. class ServiceFactoryImpl2 implements ServiceFactory{
    33. public Service service() {
    34. return new ServiceImpl2();
    35. }
    36. }