设计模式与架构02 -- 单例模式,工厂模式

2021-12-01  本文已影响0人  YanZi_33

单例模式

单例模式的实现
public class Singleton {

    //1.私有构造方法
    private Singleton() {}

    //2.在本类中创建实例对象
    private static Singleton instance = new Singleton();

    //3.提供一个公共的访问方式,让外界访问
    public static Singleton getInstance() {
        return instance;
    }
}
public class Singleton {
    //1.私有构造方法
    private Singleton() {}

    //2.定义静态成员变量
    private static Singleton instance;

    //3.在静态代码块中赋值
    static {
        instance = new Singleton();
    }
    
    public static Singleton getInstance() {
        return instance;
    }
}
public class Singleton {
    //1.私有构造方法
    private Singleton() {}

    //2.定义静态成员变量
    private static Singleton instance;

    //3.提供一个公共的访问方式,让外界访问
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
public class Singleton {
    //1.私有构造方法
    private Singleton() {}

    //2.定义静态成员变量
    private static Singleton instance;

    //3.提供一个公共的访问方式,让外界访问
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
public class Singleton {
    //1.私有构造方法
    private Singleton() {}

    //2.定义静态成员变量
    private static volatile Singleton instance;

    //3.提供一个公共的访问方式,让外界访问
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
public class Singleton {
    //1.私有构造方法
    private Singleton() {}

    //2.定义一个静态内部类
    private static class SingletonHandler {
        //在内部类中声明并初始化外部类对象
        private static Singleton INSTANCE = new Singleton();
    }

    //3.提供一个公共的访问方式,让外界访问
    public static Singleton getInstance() {
        return SingletonHandler.INSTANCE;
    }
}
public enum Singleton {
    INSTANCE;
}
import java.io.Serializable;

public class Singleton implements Serializable {
    //1.私有构造方法
    private Singleton() {}

    //2.定义一个静态内部类
    private static class SingletonHandler {
        //在内部类中声明并初始化外部类对象
        private static Singleton INSTANCE = new Singleton();
    }

    //3.提供一个公共的访问方式,让外界访问
    public static Singleton getInstance() {
        return SingletonHandler.INSTANCE;
    }
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //先写入文件
        try {
            writeObjectToFile();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //两次读取文件的 获取的单例对象不同
        try {
            readObjectFromFile();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            readObjectFromFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //往文件中写数据
    public static void writeObjectToFile() throws Exception {
        Singleton singleton = Singleton.getInstance();
        //创建对象输出流对象
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/Users/liyanyan33/Desktop/a.txt"));
        //写对象
        oos.writeObject(singleton);
        //释放资源
        oos.close();
    }

    //从文件中读数据
    public static void readObjectFromFile() throws Exception {
        //创建对象输入流对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("/Users/liyanyan33/Desktop/a.txt"));
        //读取对象
        Singleton singleton = (Singleton)ois.readObject();
        System.out.println(singleton);
        //释放资源
        ois.close();
    }
}
import java.io.Serializable;

public class Singleton implements Serializable {
    //1.私有构造方法
    private Singleton() {}

    //2.定义一个静态内部类
    private static class SingletonHandler {
        //在内部类中声明并初始化外部类对象
        private static Singleton INSTANCE = new Singleton();
    }

    //3.提供一个公共的访问方式,让外界访问
    public static Singleton getInstance() {
        return SingletonHandler.INSTANCE;
    }

    //当进行反序列化是 会自动调用改方法 将改方法的返回值直接返回
    public Object readResolve() {
        return SingletonHandler.INSTANCE;
    }
}
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //获取Singleton类的字节码对象
        Class clazz = Singleton.class;
        try {
            //获取无参构造方法
            Constructor cons = clazz.getDeclaredConstructor();
            //取消访问检查
            cons.setAccessible(true);
            //创建单例对象
            Singleton instance1 = (Singleton) cons.newInstance();
            Singleton instance2 = (Singleton) cons.newInstance();
            //不等 说明反射破坏了单例模式
            System.out.println(instance1 == instance2);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
public class Singleton  {
    
    private static boolean flag = false;
    
    //1.私有构造方法
    private Singleton() {
        //flag = true 表明非第一次访问
        //flag = false 表明第一次访问
        synchronized (Singleton.class) {
            if (flag) {
                throw  new RuntimeException("不能创建多个对象");
            }
            flag = true;
        }
    }

    //2.定义一个静态内部类
    private static class SingletonHandler {
        //在内部类中声明并初始化外部类对象
        private static Singleton INSTANCE = new Singleton();
    }

    //3.提供一个公共的访问方式,让外界访问
    public static Singleton getInstance() {
        return SingletonHandler.INSTANCE;
    }
}
public class Runtime {
    private static Runtime currentRuntime = new Runtime();

    public static Runtime getRuntime() {
        return currentRuntime;
    }

    /** Don't let anyone else instantiate this class */
    private Runtime() {}
}

工厂模式

image.png
public abstract class Coffee {

    public abstract String getName();

    public void addMilk() {
        System.out.println("加奶");
    }

    public void addSugar() {
        System.out.println("加糖");
    }
}
public class AmericanCoffee extends Coffee{
    @Override
    public String getName() {
        return "美式咖啡";
    }
}
public class LatteCoffee extends Coffee{
    @Override
    public String getName() {
        return "拿铁咖啡";
    }
}
public class CoffeeStore {
    //点咖啡
    public Coffee orderCoffee(String type) {
        Coffee coffee = null;
        if (type.equals("american")) {
            coffee = new AmericanCoffee();
        } else if (type.equals("latte")) {
            coffee = new LatteCoffee();
        } else {
            throw new RuntimeException("对不起,您所点的咖啡没有!");
        }
        coffee.addMilk();
        coffee.addSugar();
        return coffee;
    }
}
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        CoffeeStore coffeeStore = new CoffeeStore();
        coffeeStore.orderCoffee("latte");
    }
}
简单工厂模式
image.png
public abstract class Coffee {

    public abstract String getName();

    public void addMilk() {
        System.out.println("加奶");
    }

    public void addSugar() {
        System.out.println("加糖");
    }
}
public class AmericanCoffee extends Coffee{
    @Override
    public String getName() {
        return "美式咖啡";
    }
}
public class LatteCoffee extends Coffee{
    @Override
    public String getName() {
        return "拿铁咖啡";
    }
}
public class SimpleCoffeeFactory {
    public Coffee createCoffee(String type) {
        Coffee coffee = null;
        if (type.equals("american")) {
            coffee = new AmericanCoffee();
        } else if (type.equals("latte")) {
            coffee = new LatteCoffee();
        } else {
            throw new RuntimeException("对不起,您所点的咖啡没有!");
        }
        return coffee;
    }
}
public class CoffeeStore {
    //点咖啡
    public Coffee orderCoffee(String type) {
        //创建工厂
        SimpleCoffeeFactory factory = new SimpleCoffeeFactory();
        //通过工厂 获取咖啡
        Coffee coffee = factory.createCoffee(type);

        coffee.addMilk();
        coffee.addSugar();
        return coffee;
    }
}
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        CoffeeStore coffeeStore = new CoffeeStore();
        coffeeStore.orderCoffee("latte");
    }
}
public class SimpleCoffeeFactory {
    public static Coffee createCoffee(String type) {
        Coffee coffee = null;
        if (type.equals("american")) {
            coffee = new AmericanCoffee();
        } else if (type.equals("latte")) {
            coffee = new LatteCoffee();
        } else {
            throw new RuntimeException("对不起,您所点的咖啡没有!");
        }
        return coffee;
    }
}
public class CoffeeStore {
    //点咖啡
    public Coffee orderCoffee(String type) {
        //通过工厂 获取咖啡
        Coffee coffee = SimpleCoffeeFactory.createCoffee(type);

        coffee.addMilk();
        coffee.addSugar();
        return coffee;
    }
}
工厂方法模式
image.png
//抽象产品类
public abstract class Coffee {
    public abstract String getName();

    public void addMilk() {
        System.out.println("加奶");
    }

    public void addSugar() {
        System.out.println("加糖");
    }
}
//具体产品类
public class AmericanCoffee extends Coffee{
    @Override
    public String getName() {
        return "美式咖啡0";
    }
}
//具体产品类
public class LatteCoffee extends Coffee{
    @Override
    public String getName() {
        return "拿铁咖啡";
    }
}
//抽象工厂
public interface CoffeeFactory {
    public Coffee createCoffee();
}
//具体工厂类
public class AmericanCoffeeFactory implements CoffeeFactory{
    @Override
    public Coffee createCoffee() {
        return new AmericanCoffee();
    }
}
//具体工厂类
public class LatteCoffeeFactory implements CoffeeFactory{
    @Override
    public Coffee createCoffee() {
        return new LatteCoffee();
    }
}
//客户端
public class CoffeeStore {
    //持有抽象工厂
    private CoffeeFactory factory;

    public void setFactory(CoffeeFactory factory) {
        this.factory = factory;
    }

    public Coffee orderCoffee() {
        Coffee coffee = factory.createCoffee();
        coffee.addSugar();
        coffee.addMilk();
        return coffee;
    }
}
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        CoffeeStore store = new CoffeeStore();
        //在使用是初始化具体的工厂
        AmericanCoffeeFactory acf = new AmericanCoffeeFactory();
        store.setFactory(acf);
        store.orderCoffee();
    }
}
抽象工厂模式
image.png
//咖啡抽象类
public abstract class Coffee {
    public abstract String getName();

    public void addMilk() {
        System.out.println("加奶");
    }

    public void addSugar() {
        System.out.println("加糖");
    }
}
//具体产品类
public class AmericanCoffee extends Coffee{
    @Override
    public String getName() {
        return "美式咖啡";
    }
}
//具体产品类
public class LatteCoffee extends Coffee{
    @Override
    public String getName() {
        return "拿铁咖啡";
    }
}
//甜点抽象类
public abstract class Dessert {
    abstract public void show();
}
//具体产品类
public class Trimisu extends Dessert{
    @Override
    public void show() {
        System.out.println("提拉米苏");
    }
}
//具体产品类
public class MachaMourse extends Dessert{
    @Override
    public void show() {
        System.out.println("抹茶慕斯");
    }
}
//抽象工厂类
public interface DessertFactory {
    public Coffee createCoffee();
    public Dessert createDessert();
}
//具体工厂类
public class AmericanDessertFactory implements DessertFactory{
    @Override
    public Coffee createCoffee() {
        return new AmericanCoffee();
    }

    @Override
    public Dessert createDessert() {
        return new MachaMourse();
    }
}
//具体工厂类
public class ItalyDessertFactory implements DessertFactory{
    @Override
    public Coffee createCoffee() {
        return new LatteCoffee();
    }

    @Override
    public Dessert createDessert() {
        return new Trimisu();
    }
}
//客户端
public class CoffeeStore {

    private DessertFactory factory;

    public void setFactory(DessertFactory factory) {
        this.factory = factory;
    }

    public Coffee orderCoffee() {
        Coffee coffee = null;
        coffee = factory.createCoffee();
        coffee.addSugar();
        coffee.addMilk();
        return coffee;
    }

    public Dessert orderDessert() {
        Dessert dessert = null;
        dessert = factory.createDessert();
        dessert.show();
        return dessert;
    }
}
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        CoffeeStore store = new CoffeeStore();
        AmericanDessertFactory factory = new AmericanDessertFactory();
        store.setFactory(factory);
        store.orderCoffee();
        store.orderDessert();
    }
}
工厂模式的扩展
american=com.example.sign.AmericanCoffee
latt=com.example.sign.LatteCoffee
public class SimpleCoffeeFactory {

    //加载配置文件 获取配置文件中类名,并创建该对象进行存储
    //1.定义容器 存储对象
    private static HashMap<String,Coffee> map = new HashMap<>();
    //2.加载配置文件
    static {
        Properties p = new Properties();
        InputStream is = SimpleCoffeeFactory.class.getClassLoader().getResourceAsStream("bean.properties");
        //调用p的load方法 进行配置文件加载
        try {
            p.load(is);
            //从p集合中获取类名 创建对象
            Set<Object> keys = p.keySet();
            for (Object key: keys) {
                String className = p.getProperty((String) key);
                //通过反射技术创建对象
                Class clazz = Class.forName(className);
                Coffee coffee = (Coffee) clazz.newInstance();
                //将名称与对象 存储到容器中
                map.put((String) key,coffee);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static Coffee createCoffee(String name) {
        //通过名称 获取对象
        return map.get(name);
    }
}
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        CoffeeStore store = new CoffeeStore();
        Coffee coffee = store.orderCoffee("latte");
        System.out.println(coffee.getName());
    }
}
上一篇下一篇

猜你喜欢

热点阅读