设计模式之工厂和单例

工厂模式实例

//定义一个接口:Vehicle

 interface Vehicle{
 void work();
}

//定义一个实现类:Car

 class Car implements Vehicle{
   @Override
   public void work(){
      System.out.println("I am building a Car");
    }
}

//定义一个实现类:Train

 class Train implements Vehicle{
    @Override
    public void work(){
        System.out.println("I am building a train");
    }
}
 public class factory{
 //根据不同需求返回不同实现类的方法   
     public Vehicle needs(String s){
        if(s.equals("Car")){
          return new Car();
        }else if (s.equals("Train")) {
            return new Train();
        }
        return null;
     }

     public static void main (String args[]){
         factory f =  new factory();
         Vehicle v=f.needs("Car");
         v.work();
         Vehicle v1=f.needs("Train");
         v1.work();
     }
 }

运行结果 :
—I am building a Car
—I am building a train

单利模式实例

懒汉式

public class Singleton {  
    private static Singleton instance;  
    private Singleton (){}  
    public static synchronized Singleton getInstance() {  
    if (instance == null) {  
        instance = new Singleton();  
    }  
    return instance;  
    }  
} 

饿汉式

public class Singleton {  
private static Singleton instance = new Singleton();  
private Singleton (){}  
public static Singleton getInstance() {  
return instance;  
}  

}

    原文作者:设计模式
    原文地址: https://segmentfault.com/a/1190000009694749
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞