1.单例模式
1.单例类只能有一个实例
2.单例类必须自己创建自己的唯一实例
3.单例类必须给所有其他对象提供这一实例
单例模式确保某一个类只有一个实例,选择单例模式就是为了避免不一致状态.
所以单例对象通常作为程序存放配置信息的载体.
1.饿汉式
public class Singlenton {
private static Singlenton singlenton = new Singlenton();
private Singlenton(){ }
public Singlenton getInstance(){
return singlenton;
}
}
2.懒汉式
public class Singlenton {
private static Singlenton singlenton = null;
public static synchronized Singlenton getInstance(){
if (singlenton == null){
singlenton = new Singlenton();
}
return singlenton;
}
}
3.枚举
enum Singlenton2{
Singlenton2;
}
4.静态内部类
public class Singlenton {
private static class SingletonHolder{
private static final Singlenton INSTANCE =new Singlenton();
}
private Singlenton(){}
public static final Singlenton getInstance(){
return SingletonHolder.INSTANCE;
}
}
5.静态代码块
class Singlenton4{
static {
Singlenton4 singlenton4 = new Singlenton4();
}
}
2.工厂模式
1.简单工厂模式:不利于产生系列产品
2.工厂方法模式:又称多形性工厂
3.抽象工厂模式
工厂方法模式
//抽象产品角色
public interface Moveable {
void run();
}
//具体产品角色
class Plane implements Moveable{
@Override
public void run() {
System.out.println("Plane move");
}
}
//抽象工厂
abstract class VehicleFactory{
abstract Moveable create();
}
//具体工厂
class PlaneFactory extends VehicleFactory{
@Override
Moveable create() {
return new Plane();
}
}
抽象工厂模式
public abstract class AbstractFactory {
public abstract Vehicle createVehicle();
}
class DefaultFactory extends AbstractFactory{
@Override
public Vehicle createVehicle() {
return new Car();
}
}
class Test{
public static void main(String[] args) {
AbstractFactory abstractFactory = new DefaultFactory();
Vehicle v = abstractFactory.createVehicle();
v.run();
}
}
网友评论