单例模式

1. 懒汉单例模式

class A {
    private static A a = null ;
    private A() {}
    public static A getAInstance() {
        a = new A();
        return a ;
    }       
}

 

2.恶汉单例模式

class B {
    private static B b = new B() ;
    private B() {}
    public static B getBInstance() {
        return b ;
    }       
}

单例模式中,只有一个实例。

3.工厂模式

import java.io.*;
class CarFactory {    
  
  /**
  * 单例模式 
  */
private static CarFactory factory = null; private CarFactory (){} public static CarFactory getFactoryInstance(){ factory = new CarFactory(); return factory; } Car buildCar(String CarName) { switch(CarName) { case "BMW" : return new BMW(); case "QQ" : return new QQ(); default : break; } return null; } } interface Car { void build(); } class BMW implements Car { public void build(){ System.out.println("我是宝马我自豪,别摸我"); } } class QQ implements Car { public void build(){ System.out.println("我是QQ我小巧,0油耗"); } } public class Test04 { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader( new InputStreamReader(System.in) ); System.out.println("要什么车?(BMW ? QQ ?)"); String input = reader.readLine(); CarFactory factory = CarFactory.getFactoryInstance(); Car car = factory.buildCar(input); car.build(); } }

 

3.工厂方法模式

import java.io.*;
interface Factory {
    Goods build();
}
//汽车工厂
class CarFactory implements Factory {
    public Goods build() {
        return new Car();
    }
}
//
class WaterFactory implements Factory {
    public Goods build() {
        return new Water();
    }
}
interface Goods {
    void order() ;
}
class Car implements Goods {
    public void order(){
        System.out.println("汽车!开走吧!");
    }
}
class Water implements Goods {
    public void order(){
        System.out.println("水!喝吧!");
    }
}

public class Test05 {
    public static void main(String[] args) throws Exception{
        BufferedReader reader = new BufferedReader(
            new InputStreamReader(System.in)
        ); 
        System.out.println("要什么东西?(CarFactory ? WaterFactory ?)");
        String input = reader.readLine();
        Class factoryClass = Class.forName(input);
        Factory factory = (Factory)factoryClass.newInstance();
        //Factory factory = new WaterFactory();
        Goods goods = factory.build();
        goods.order();
    }
}

 

posted @ 2017-07-07 16:59  Zero豪  阅读(195)  评论(0编辑  收藏  举报