Garantir que uma classe tenha somente uma instância e fornecer um ponto global de acesso para a mesma.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package singleton;
/**
*
* @author patrickbelem
*/
public class Car {
private String model;
private String category;
//public abstract void showInformation();
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package singleton;
/**
*
* @author patrickbelem
*/
public class Client {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
SingletonCarFactory factory = SingletonCarFactory.getInstancy();
// SingletonCarFactory factory1 = new SingletonCarFactory();
factory.buildCar("Palio", "Hatch");
factory.buildCar("Gol", "hatch");
factory.buildCar("Siena", "Sedan");
factory.buildCar("Voyage", "Sedan");
System.out.println(factory.getTotal());
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package singleton;
/**
*
* @author patrickbelem
*/
public class SingletonCarFactory {
public int totalCars;
public static SingletonCarFactory instancy;
private SingletonCarFactory(){ //Privated constructor
}
public Car buildCar(String model, String category){
Car car = new Car();
car.setModel(model);
car.setCategory(category);
totalCars++;
return car;
}
public static SingletonCarFactory getInstancy() {
if (instancy == null)
instancy = new SingletonCarFactory();
return instancy;
}
public String getTotal(){
return "Total de carros Criados: " + totalCars;
}
}