标签:java设计模式 工厂模式 singleton 创建型
public class Singleton { private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } private Singleton (){} public static final Singleton getInstance() { return SingletonHolder.INSTANCE; } }
public enum EasySingleton{ INSTANCE; }
//抽象产品角色 public interface Car { public void drive(); } //具体产品角色一 public class Benz implements Car { public void drive() { System.out.println("Driving Benz "); } } //具体产品角色二 public class Bmw implements Car { public void drive() { System.out.println("Driving Bmw "); } } //工厂类角色 public class Driver { //工厂方法.注意 返回类型为抽象产品角色 public static Car driverCar(String s) throws Exception { //判断逻辑,返回具体的产品角色给Client if (s.equalsIgnoreCase("Benz")) return new Benz(); else if (s.equalsIgnoreCase("Bmw")) return new Bmw(); else throw new Exception(); } } //欢迎暴发户出场...... public class Magnate { public static void main(String[] args) { Car car = Driver.driverCar("benz");//告诉司机我今天坐奔驰 car.drive();//下命令:开车 } }
标签:java设计模式 工厂模式 singleton 创建型
原文地址:http://blog.csdn.net/pengkv/article/details/44199457