设计模式 单例模式(懒汉锇汉) 工厂模式

--常用设计模式之一 单例模式

    一个类只能有一个实例而且客户可以从一个众所周知的访问点访问它 特点是构造函数私有 单例模式分为两个模式 懒汉模式与锇汉模式  懒汉模式表示不使用就不创建实例,当外部调用时才创建实例  锇汉模式表示无论外部是否调用 都先自己创建一个实例

懒汉模式

public class Singleton {

    private static Singleton singleton=null;

    private Singleton(){

    

    }

    public Singleton getInstance(){

        if(singleton==null){

            return singleton=new Singleton();

        }

        return singleton;

    }

}

锇汉模式

public class Singleton {

    private static Singleton singleton=new Singleton();

    private Singleton(){

    

    }

    public Singleton getInstance(){

        return singleton;

    }

}

--常用设计模式之二 工厂模式

定义一个用于创建对象的接口,让子类决定实例化哪一个类

接口
public interface Fruit {  
    public void print();  

}  

2个实现类
public class Apple implements Fruit{  
    @Override  
    public void print() {  
        System.out.println("我是一个苹果");  
    }  
}  
public class Orange implements Fruit{  
    @Override  
    public void print() {  
        System.out.println("我是一个橘子");  
    }  
}  

工厂类
public class FruitFactory {  
    public Fruit produce(String type){  
        if(type.equals("apple")){  
            return new Apple();  
        }else if(type.equals("orange")){  
            return new Orange();  
        }else{  
            System.out.println("请输入正确的类型!");    
            return null;   
        }  
    }  

设计模式  分为三种类型  23种

--1.创建型模式  5种

单例模式(Singleton) 工厂模式(Factor Method) 原型模式(Prototype)  抽象工厂模式(Abstract) 建造者模式(Builder)

--2.结构型模式  7种

适配器模式(Adapter)  桥接模式(Bridge) 装饰模式(Decorator)  组合模式(Composite) 外观模式(Facade) 享元模式(Flyweight)  代理模式(Proxy)

--3.行为型模式  11种

模板方法模式(Template Method)  命令模式(Command)  迭代器模式(Iterator)  观察者模式(Observer)  中介模式(Mediator)  备忘录模式(Memento)  解释器模式(Interpreter)  状态模式(State)  策略模式(Strategy)  职责链模式(责任链模式 Chain of Responsibility)  访问者模式(Visitor)


猜你喜欢

转载自blog.csdn.net/qq_40899182/article/details/81011249