工厂模式-之1

这个代码是《java编程思想》中的例子,其实不仅仅是工厂模式的体现,还有饿汉式单例模式的应用。

package innerclasses;

//: innerclasses/Factories.java
import static net.mindview.util.Print.*;

interface Service
{
    void method1();

    void method2();
}

interface ServiceFactory
{
    Service getService();
}
//单例模式
class Implementation1 implements Service
{
    private Implementation1()
    {
    }

    public void method1()
    {
        print("Implementation1 method1");
    }

    public void method2()
    {
        print("Implementation1 method2");
    }

    public static ServiceFactory factory = new ServiceFactory()
    {
        public Service getService()
        {
            return new Implementation1();
        }
    };
}

class Implementation2 implements Service
{
    private Implementation2()
    {
    }

    public void method1()
    {
        print("Implementation2 method1");
    }

    public void method2()
    {
        print("Implementation2 method2");
    }

    public static ServiceFactory factory = new ServiceFactory()
    {
        public Service getService()
        {
            return new Implementation2();
        }
    };
}

public class Factories
{
    public static void serviceConsumer(ServiceFactory fact)
    {
        Service s = fact.getService();
        s.method1();
        s.method2();
    }

    public static void main(String[] args)
    {
        serviceConsumer(Implementation1.factory);
        // Implementations are completely interchangeable:
        serviceConsumer(Implementation2.factory);
    }
}

你可能感兴趣的:(工厂模式-之1)