1、單例模式安全
一、餓漢模式spa
public class Singleton { private static Singleton uniqueInstance = new Singleton(); private Singleton() { } }
二、懶漢式-線程安全線程
public class Singleton { private static Singleton uniqueInstance; private Singleton() { } public static synchronized Singleton getUniqueInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } }
2、工廠模式code
一、簡單工廠模式blog
public interface Product { } public class ConcreteProduct implements Product { } public class ConcreteProduct1 implements Product { } public class ConcreteProduct2 implements Product { } public class Client { public static void main(String[] args) { int type = 1; Product product; if (type == 1) { product = new ConcreteProduct1(); } else if (type == 2) { product = new ConcreteProduct2(); } else { product = new ConcreteProduct(); } // do something with the product } }
二、工廠方法get
public abstract class Factory { abstract public Product factoryMethod(); public void doSomething() { Product product = factoryMethod(); // do something with the product } } public class ConcreteFactory extends Factory { public Product factoryMethod() { return new ConcreteProduct(); } } public class ConcreteFactory1 extends Factory { public Product factoryMethod() { return new ConcreteProduct1(); } } public class ConcreteFactory2 extends Factory { public Product factoryMethod() { return new ConcreteProduct2(); } }
三、抽象工廠模式it
public class AbstractProductA { } public class AbstractProductB { } public class ProductA1 extends AbstractProductA { } public class ProductA2 extends AbstractProductA { } public class ProductB1 extends AbstractProductB { } public class ProductB2 extends AbstractProductB { } public abstract class AbstractFactory { abstract AbstractProductA createProductA(); abstract AbstractProductB createProductB(); } public class ConcreteFactory1 extends AbstractFactory { AbstractProductA createProductA() { return new ProductA1(); } AbstractProductB createProductB() { return new ProductB1(); } } public class ConcreteFactory2 extends AbstractFactory { AbstractProductA createProductA() { return new ProductA2(); } AbstractProductB createProductB() { return new ProductB2(); } } public class Client { public static void main(String[] args) { AbstractFactory abstractFactory = new ConcreteFactory1(); AbstractProductA productA = abstractFactory.createProductA(); AbstractProductB productB = abstractFactory.createProductB(); // do something with productA and productB } }