JAVA设计模式(创建型)应用及解析

创建型设计模式分类

工厂方法模式(Factory Method): 定义一个创建对象的接口,但由子类决定需要实例化哪一个类。 工厂方法使得子类实例化的过程推迟
抽象工厂模式(Abstract Factory): 提供一个接口,可以创建一系列相关或相互依赖的对象,而无需指定它们具体的类
构建器模式(Builder): 将一个复杂类的表示与其构造相分离,使得相同的构建过程能够得出不同的表示
单例模式(Singleton): 保证一个类只有一个实例,并提供一个访问它的全局访问点
原型模式(Prototype): 用原型实例指定创建对象的类型,并且通过拷贝这个原型来创建新的对象

正文开始====================================

工厂方法模式(Factory Method)

适用场景:创建对象需要大量的重复代码。客户端(应用层)不依赖于产品类实例如何被创建和实现等细节。一个类通过其子类来指定创建哪个对象。
特点:1.用户只需要关系所需产品对应的工厂,无须关心创建细节。2.加入新产品符合开闭原则,提高了系统的可扩展性。
缺点:类的数量容易过多,增加了代码结构的复杂度。增加了系统的抽象性和理解难度。

public class BMW {
    public BMW(){}
}


public class BMW320 extends BMW {
    public BMW320() {
        System.out.println("制造-->BMW320");
    }
}


public class BMW523  extends BMW{
    public BMW523(){
        System.out.println("制造-->BMW523");
    }
}

//抽象的工厂类Factory
public interface FactoryBMW {
    BMW createBMW();
}

public class FactoryBMW320  implements FactoryBMW{

    @Override
    public BMW320 createBMW() {
        return new BMW320();
    }

}


public class FactoryBMW523  implements FactoryBMW {
    @Override
    public BMW523 createBMW() {
        return new BMW523();
    }
}

public class FactoryMethodTest {

    public static void main(String[] args) {
        FactoryBMW320 factoryBMW320 = new FactoryBMW320();
        BMW320 bmw320 = factoryBMW320.createBMW();

        FactoryBMW523 factoryBMW523 = new FactoryBMW523();
        BMW523 bmw523 = factoryBMW523.createBMW();
//
//        System.out.println(bmw320);
//        System.out.println(bmw523);
    }


}

抽象工厂模式(Abstract Factory)

适用场景:1.客户端(应用层)不依赖于产品类实例如何被创建和实现等细节。
2.强调一系列相关的产品对象(属于同一产品族)一起使用创建对象需要大量重复的代码。
3.提供一个产品类的库,所有的产品以同样的接口出现,从而使客户端不依赖于具体实现。
优点:当一个产品族中的多个对象被设计成一起工作时,它能保证客户端始终只使用同一个产品族中的对象。
缺点:当产品族中需要增加一个新的产品时,所有的工厂类都需要进行修改。


//空调以及型号
public interface Aircondition {
}


public class AirconditionA  implements Aircondition{
    public AirconditionA(){
        System.out.println("制造-->AirconditionA");
    }
}

public class AirconditionB  implements Aircondition{
    public AirconditionB(){
        System.out.println("制造-->AirconditionB");
    }
}

//发动机以及型号
public interface Engine {

}
public class EngineA  implements Engine{
    public EngineA(){
        System.out.println("制造-->EngineA");
    }
}

public class EngineB implements Engine{
    public EngineB(){
        System.out.println("制造-->EngineB");
    }
}

//创建工厂的接口
public interface  AbstractFactory {

    //制造发动机
    Engine createEngine();
    //制造空调
    Aircondition createAircondition();

}
//为宝马320系列生产配件
public class FactoryBMW320  implements AbstractFactory{
    @Override
    public Engine createEngine() {
        return new EngineA();
    }
    @Override
    public Aircondition createAircondition() {
        return new AirconditionA();
    }
}

//宝马523系列生产配件
public class FactoryBMW523  implements AbstractFactory {
    @Override
    public Engine createEngine() {
        return new EngineB();
    }
    @Override
    public Aircondition createAircondition() {
        return new AirconditionB();
    }
}

public class Customer {

    public static void main(String[] args){
        //生产宝马320系列配件
        FactoryBMW320 factoryBMW320 = new FactoryBMW320();
        factoryBMW320.createEngine();
        factoryBMW320.createAircondition();

        //生产宝马523系列配件
        FactoryBMW523 factoryBMW523 = new FactoryBMW523();
        factoryBMW523.createEngine();
        factoryBMW523.createAircondition();
    }
}


构建器模式(Builder)

适用场景:适用于创建对象需要很多步骤,但是步骤顺序不一定固定。如果一个对象有非常复杂的内部结构(属性),把复杂对象的创建和使用进行分离。
特点:1.封装性好,创建和使用分离 2.扩展性好,建造类之间独立,在一定程度上解耦
缺点:1.会产生多余的Builder对象 2.产品内部发生变化,建造者也需要修改,成本可能会随着业务场景的改变而改变

//产品类 电脑
public class Computer {

    private String motherboard;
    private String cpu;
    private String memory;

    public Computer() {
    }

    public Computer(String motherboard, String cpu, String memory) {
        this.motherboard = motherboard;
        this.cpu = cpu;
        this.memory = memory;
    }

    public String getMotherboard() {
        return motherboard;
    }

    public void setMotherboard(String motherboard) {
        this.motherboard = motherboard;
    }

    public String getCpu() {
        return cpu;
    }

    public void setCpu(String cpu) {
        this.cpu = cpu;
    }

    public String getMemory() {
        return memory;
    }

    public void setMemory(String memory) {
        this.memory = memory;
    }

    @Override
    public String toString() {
        return "Computer{" +
                "motherboard='" + motherboard + '\'' +
                ", cpu='" + cpu + '\'' +
                ", memory='" + memory + '\'' +
                '}';
    }
}

// 抽象 builder类(接口) 组装电脑
public interface ComputerBuilder {

    Computer computer = new Computer();

    void buildMotherboard();
    void buildCpu();
    void buildMemory();

    Computer build();

}

//具体 builder类
public class AsusComputerBuilder implements ComputerBuilder {


    @Override
    public void buildMotherboard() {
        computer.setMotherboard("Extreme主板");
    }

    @Override
    public void buildCpu() {
        computer.setCpu("Inter 12900KS");
    }

    @Override
    public void buildMemory() {
        computer.setMemory("芝奇幻峰戟 16G*2");
    }

    @Override
    public Computer build() {
        return computer;
    }
}


/**
 * 指挥者类
 *
 * 指挥者类ComputerDirector在建造者模式中具有很重要的作用,它用于指导具体构建者如何构建产品,
 * 控制调用先后次序,并向调用者返回完整的产品类
 */
public class ComputerDirector {

    private ComputerBuilder computerBuilder;

    public Computer construct() {
        computerBuilder.buildMotherboard();
        computerBuilder.buildCpu();
        computerBuilder.buildMemory();
        return computerBuilder.build();
    }

    public ComputerDirector(ComputerBuilder computerBuilder) {
        this.computerBuilder = computerBuilder;
    }
}

public class BuilderTest {

    // 测试
    public static void main(String[] args) {
        ComputerDirector computerDirector = new ComputerDirector(new AsusComputerBuilder());
        // Computer(motherboard=Extreme主板, cpu=Inter 12900KS, memory=芝奇幻峰戟 16G*2)
        System.out.println(computerDirector.construct());
    }

}

单例模式(Singleton)

饿汉式

适用场景:需要确保在任何情况下绝对只需要一个实例
特点:主要特点是在类加载时就创建并初始化单例对象,保证了在多线程环境下的线程安全性
缺点:1.提前占用内存空间,饿汉式在类加载时就创建单例对象,无论是否会使用该对象,都会占用一定的内存空间。
2.无法延迟加载
3.可能造成资源浪费,如果在程序运行过程中始终没有使用该单例对象,而它又是在类加载时就创建的,就会造成资源的浪费
4.无法处理异常情况,如果在单例对象的初始化过程中发生异常,可能会导致整个应用程序启动失败。这是因为单例对象的创建发生在类加载阶段,而异常无法捕获和处理。

public class Singleton1 {
    //构造方法私有化。目的:防止外面调用造对象  如果不将其定义成私有的,那么便可以在外面不断的创建类对象 无法做到只有一个对象
    private Singleton1(){}
    //饿汉式创建单例模式
    private static Singleton1 singleton1 = new Singleton1();
    //提供公共的静态方法,返回类对象
    public static Singleton1 getSingleton1() {
        return singleton1;
    }

}

public class Singleton1Test {

    public static void main(String[] args) {
        Singleton1 singleton1 = Singleton1.getSingleton1();//通过调用内部类的方法 从而调用该对象
        Singleton1 singleton2 = Singleton1.getSingleton1();//通过调用内部类的方法 从而调用该对象

        System.out.println(singleton1);
        System.out.println(singleton2);
    }
}

懒汉式

适用场景:需要确保在任何情况下绝对只需要一个实例
特点:第一次调用才初始化,避免内存浪费。
缺点:首次使用对象时,需要等待对象的创建,而且每次都需要判断对象是否为空,运行效率较低。

public class Singleton2 {

    private static Singleton2 singleton2;

    /*
     * 懒汉式创建单例模式 由于懒汉式是非线程安全, 所以加上线程锁保证线程安全
     */
    public static synchronized Singleton2 getInstance(){
        if(singleton2 == null){
            singleton2 = new Singleton2();
        }
        return singleton2;
    }

}


public class Singleton2Test {

    public static void main(String[] args) {
        Singleton2 instance1 = Singleton2.getInstance();
        Singleton2 instance2 = Singleton2.getInstance();

        System.out.println(instance1);
        System.out.println(instance2);

        System.out.println(instance1 == instance2);
    }
}

静态内部类
适合在需要频繁使用、且资源占用较小的单例对象时使用

优点:1.使用了Java类加载机制,单例对象在类加载阶段就已经创建好且只会创建一次,因此是线程安全的。
2.利用静态内部类特点实现延迟加载,效率高
缺点: 1.可能会增加类的数量,因为需要一个静态内部类来保存单例对象
2.第一次加载时可能会略微增加启动时间

public class Singleton3 {

    private Singleton3(){}

    private static class SingletonHolder{

        private static final Singleton3 INSTANCE = new Singleton3();
    }

    public static Singleton3 getInstance(){
        return SingletonHolder.INSTANCE;
    }

}

public class Singleton3Test {

    public static void main(String[] args) {
        Singleton3 instance1 = Singleton3.getInstance();
        Singleton3 instance2 = Singleton3.getInstance();
        System.out.println(instance1);
        System.out.println(instance2);
    }

}

原型模式(Prototype)

特点:1.可以避免创建复杂对象时的开销,在性能上比直接 new 一个对象更加优良。
2.原型模式能够保护现有对象的状态。
缺点:1.在实现原型模式时,必须注意克隆对象的所有属性,包括私有属性和引用类型属性。
2.如果原型对象的属性包含大量数据,那么复制对象的成本将会很高。
3.需要实现Cloneable接口,并且需要重写clone方法,这会增加代码量和复杂度。

public class Student  implements Cloneable {
    private String name;
    private String sex;
    private Integer age;

    public Student() {
    }

    public Student(String name, String sex, Integer age) {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                '}';
    }


//    @Override
//    protected Object clone() throws CloneNotSupportedException {//默认的clone
//        return super.clone();
//    }
    //重写clone方法,或者用默认的clone方法也行,只不过调用时候需要抛异常
    @Override
    protected Object clone()  {
        Student student = null;
        try {
            student = (Student)super.clone();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return student;
    }

}

public class PrototypeTest {

    public static void main(String[] args) throws Exception{
        Student stu1 = new Student("张三", "男", 18);
        Student stu2 = (Student)stu1.clone();//复制对象
        stu2.setName("李四");
        System.out.println(stu1);// Student(name=张三, sex=男, age=18)
        System.out.println(stu2);// Student(name=李四, sex=男, age=18)
    }

}

参考总结而来,供学习!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值