Java版本设计模式——创建型模式

本文介绍了Java中创建型设计模式,包括单例模式(懒汉模式、双重校验、静态内部类、枚举方式)、静态工厂模式、抽象工厂模式、建造者模式和原型模式。详细阐述了各种模式的实现方式、优缺点以及适用场景。

Java版本设计模式——创建型模式

1、创建型模式

1.1、单例模式

单例模式顾名思义,就是全局就只有一个类。该类负责创建自己,同时需要保证只有单个对象被创建。单例模式有多种实现方案,具体如下:

1.1.1、懒汉模式

懒汉模式可以理解为,用到时再创建,否则不创建。

1.1.1.1、简单静态属性方式

此方式简单易懂,但线程不安全。

/**
 * 类似功能描述:
 *
 * @author Jeffwu
 */
public class Singleton {

    private static Singleton singleton = null;
    private Singleton(){}

    public static Singleton getInstance() {
    	//不安全点
        if (null == singleton) {
            singleton = new Singleton();
        }

        return singleton;
    }

    public static void main(String[] args) {
        Singleton instance = Singleton.getInstance();
        System.out.println(instance);
    }
}

改进版线程安全

/**
 * 类似功能描述:
 *
 * @author Jeffwu
 */
public class Singleton {

    private static Singleton singleton = null;
    private Singleton(){}

    public static Singleton getInstance() {
    	//不安全点
        if (null == singleton) {
            singleton = new Singleton();
        }

        return singleton;
    }

    public static synchronized void main(String[] args) {
        Singleton instance = Singleton.getInstance();
        System.out.println(instance);
    }
}

1.1.1.2、双重校验方式

该方式能实现懒加载,线程安全。不过此实现方式较为复杂。

/**
 * 类似功能描述:
 *
 * @author Jeffwu
 */
public class Singleton {

    private static volatile Singleton singleton = null;
    private Singleton(){}

    public static synchronized Singleton getInstance() {
        if (null == singleton) {
            synchronized (Singleton.class) {
                if (null == singleton) {
                    singleton = new Singleton();
                }
            }
        }

        return singleton;
    }

    public static void main(String[] args) {
        Singleton instance = Singleton.getInstance();
        System.out.println(instance);
    }
}

1.1.1.3、静态内部类方式

该方式能实现懒加载,线程安全。不过此实现方式难度一般。之所以能懒加载与线程安全,得益于JVM的类加载。

/**
 * 类似功能描述:
 *
 * @author Jeffwu
 */
public class Singleton {

    static class SingletonHolder {
        private final static Singleton singleton = new Singleton();
    }
    private Singleton(){}

    public static Singleton getInstance() {
        return SingletonHolder.singleton;
    }

    public static void main(String[] args) {
        Singleton instance = Singleton.getInstance();
        System.out.println(instance);
    }
}
1.1.1.4、枚举方式

枚举是单例实现的最佳方法。因它简洁,自动支持序列化机制,防止反序列化重新创建对象,绝对防止多次实例化。线程安全,非懒加载方式。

/**
 * 类似功能描述:
 *
 * @author Jeffwu
 */
public enum Singleton {
    
    SINGLETON;

    public void test() {
        
    }

}
1.1.2、恶汉模式

恶汉模式可以理解为,不管用不用我,我都在这里。

/**
 * 类似功能描述:
 *
 * @author Jeffwu
 */
public class Singleton {

    private final static Singleton SINGLETON = new Singleton();

    public Singleton getSingleton() {
        return SINGLETON;
    }
}

1.2、静态工厂模式(方法)

**优点:**工厂模式提供一种将对象的实例化过程封装在工厂类中的方式。使用工厂模式,可以将对象的创建与使用进行解耦,提供一种统一的接口创建不同的对象。
**缺点:**新增新对象,需要改动工厂类的代码。

/**
 * 类似功能描述: 工厂设计模式:
 * 1、静态工厂
 * 2、抽象工厂
 *
 * @author Jeffwu
 */
public class ProductFactoryDemo {

    public static void main(String[] args) {
        Speed bicycle = SpeedFactory.speed("Bicycle");
        System.out.println("自行车速度:"+bicycle.speed());

        Speed saloon = SpeedFactory.speed("Saloon");
        System.out.println("轿车速度:"+saloon.speed());

        Speed truck = SpeedFactory.speed("Truck");
        System.out.println("卡车速度:"+truck.speed());
    }
}

/**
 * 获取速度的接口
 */
interface Speed {
    int speed();
}


/**
 * 获取轿车速度
 */
class Saloon implements Speed {
    @Override
    public int speed() {
        return 380;
    }
}
/**
 * 获取卡车速度
 */
class Truck implements Speed {
    @Override
    public int speed() {
        return 120;
    }
}
/**
 * 获取自行车速度
 */
class Bicycle implements Speed {
    @Override
    public int speed() {
        return 20;
    }
}
/**
 * 获取速度的工厂
 */
class SpeedFactory {

    static Speed speed(String type) {
        Speed speed = null;
        if ("Saloon".equals(type)) {
            speed = new Saloon();
        } else if ("Truck".equals(type)) {
            speed = new Truck();
        } else if ("Bicycle".equals(type)) {
            speed = new Bicycle();
        }
        return speed;
    }
}

1.3、抽象工厂模式

**优点:**抽象工厂是负责创建其他工厂,其方法只负责创建相关的对象工厂,不需要显式的知道他们的类。通过抽象工厂可以将客户端与具体产品的创建过程进行解耦。
**缺点:**新增一类工厂时,需要改动的代码很多。如抽象工厂要提供新抽象方法,之前实现的具体工厂实现抽象类新增的方法,工厂提供类获取工厂的方法。
**改进:**①抽象工厂的方法在抽象类定义,不做具体实现,由子类自行实现。②使用接口(JDK8),接口类实现方法,但不做具体实现。

package com.wq.fx;

/**
 * 类似功能描述: 工厂设计模式:
 * 1、静态工厂
 * 2、抽象工厂
 *
 * @author Jeffwu
 */
public class ProductFactoryDemo {


    public static void main(String[] args) {
        AbstractFactory speedFactory = FactoryProducer.getFactory("Speed");

        Speed bicycle = speedFactory.getSpeed("Bicycle");
        System.out.println("自行车速度:"+bicycle.speed());

        Speed saloon = speedFactory.getSpeed("Saloon");
        System.out.println("轿车速度:"+saloon.speed());

        Speed truck = speedFactory.getSpeed("Truck");
        System.out.println("卡车速度:"+truck.speed());


        AbstractFactory colorFactory = FactoryProducer.getFactory("color");
        Color red = colorFactory.getColor("Red");
        System.out.println("颜色:"+red.color());

        Color green = colorFactory.getColor("Green");
        System.out.println("颜色:"+green.color());

        Color yellow = colorFactory.getColor("Yellow");
        System.out.println("颜色:"+yellow.color());
    }
}


interface Speed {
    int speed();
}

class Saloon implements Speed {
    @Override
    public int speed() {
        return 380;
    }
}

class Truck implements Speed {
    @Override
    public int speed() {
        return 120;
    }
}

class Bicycle implements Speed {
    @Override
    public int speed() {
        return 20;
    }
}

/**
 * 获取颜色
 */
interface Color {
    String color();
}

class Red implements Color {
    @Override
    public String color() {
        return "红色";
    }
}

class Green implements Color {
    @Override
    public String color() {
        return "绿色";
    }
}

class Yellow implements Color {
    @Override
    public String color() {
        return "黄色";
    }
}

abstract class AbstractFactory {

    public abstract Speed getSpeed(String type);

    public abstract Color getColor(String type);
}

class SpeedFactory extends AbstractFactory {

    public Speed getSpeed(String type) {
        Speed speed = null;
        if ("Saloon".equals(type)) {
            speed = new Saloon();
        } else if ("Truck".equals(type)) {
            speed = new Truck();
        } else if ("Bicycle".equals(type)) {
            speed = new Bicycle();
        }
        return speed;
    }

    @Override
    public Color getColor(String type) {
        //速度工厂不对这进行实现
        return null;
    }
}

class ColorFactory extends AbstractFactory {

    public Speed getSpeed(String type) {
        //颜色工厂不对这进行实现
        return null;
    }

    @Override
    public Color getColor(String type) {
        Color color = null;
        if ("Red".equals(type)) {
            color = new Red();
        } else if ("Green".equals(type)) {
            color = new Green();
        } else if ("Yellow".equals(type)) {
            color = new Yellow();
        }
        return color;
    }
}

class FactoryProducer {


    public static AbstractFactory getFactory(String factoryType) {
        AbstractFactory factory = null;
        if ("Speed".equalsIgnoreCase(factoryType)) {
            factory = new SpeedFactory();
        } else if ("color".equalsIgnoreCase(factoryType)) {
            factory = new ColorFactory();
        }
        return factory;
    }
}

1.4、建造者模式

该模式会一步步的构造好最终的对象,把一些复杂化简化一些。该builder独立于其他对象。


/**
 * 类似功能描述:
 *
 * @author Jeffwu
 */
public class BuilderDemo {

    static class Person {
        String id;
        String name;
        String sex;
        String age;
        String address;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        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 String getAge() {
            return age;
        }

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

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

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

    static class PersonBuilder {

        private final Person person;

        public PersonBuilder() {
            person = new Person();
        }


        public PersonBuilder id(String id) {
            person.setId(id);
            return this;
        }

        public PersonBuilder name(String name) {
            person.setName(name);
            return this;
        }
        public PersonBuilder age(String age) {
            person.setAge(age);
            return this;
        }
        public PersonBuilder sex(String sex) {
            person.setSex(sex);
            return this;
        }

        public PersonBuilder address(String address) {
            person.setAddress(address);
            return this;
        }

        public Person build() {
            return this.person;
        }
    }

    public static void main(String[] args) {
        Person build = new PersonBuilder().id("1").age("20").sex("男").name("测试").address("测试").build();
        System.out.println(build);
    }
}

JDK1.8以上(含)实现方式

package com.wq.fx;


import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * 类似功能描述:
 *
 * @author Jeffwu
 */
public class Jdk8Builder<T> {
    private final Supplier<T> constructor;
    private final List<Consumer<T>> fields = new ArrayList<>();

    public Jdk8Builder(Supplier<T> constructor) {
        this.constructor = constructor;
    }

    public <U> Jdk8Builder<T> with(BiConsumer<T, U> consumer, U v) {
        Consumer<T> tt = in -> consumer.accept(in, v);
        fields.add(tt);
        return this;
    }
    public <U> Jdk8Builder<T> with(boolean condition, BiConsumer<T, U> consumer, U v) {
        if (condition && null != v) {
            Consumer<T> tt = in -> consumer.accept(in, v);
            fields.add(tt);
        }
        return this;
    }

    public T build() {

        if (null == constructor) {
            return null;
        }

        T t = constructor.get();
        fields.forEach(e -> e.accept(t));
        return t;
    }

    public static void main(String[] args) {
        Person person = new Jdk8Builder<>(Person::new)
                .with(Person::setId, "1")
                .with(Person::setName, "测试")
                .with(Person::setAge, "18")
                .with(Person::setSex, "女")
                .with(Person::setAddress, "测试地址")
                .build();
        System.out.println(person);
    }

}

class Person {
    String id;
    String name;
    String sex;
    String age;
    String address;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    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 String getAge() {
        return age;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

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

1.5、原型模式

此类模式是在直接创建对象代价较大时采用的一种模式,该模式是通过克隆拷贝原型对象创建新对象。


import java.util.HashMap;
import java.util.Map;

/**
 * 类似功能描述:
 *
 * @author Jeffwu
 */
public class PrototypeDemo {

    public static void main(String[] args) {
        Color color = ColorProducer.getColor(1);
        System.out.println(color);
        
        Color color2 = ColorProducer.getColor(2);
        System.out.println(color2);
    }

    static abstract class Color implements Cloneable {
        protected int type;
        protected String color;

        @Override
        protected Object clone() {
            try {
                return super.clone();
            } catch (CloneNotSupportedException e) {
                return null;
            }
        }

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }

        public String getColor() {
            return color;
        }

        public void setColor(String color) {
            this.color = color;
        }

        @Override
        public String toString() {
            return "Color{" +
                    "type=" + type +
                    ", color='" + color + '\'' +
                    '}';
        }
    }

    static class Red extends Color {
        public Red() {
            type = 1;
            color = "红色";
        }
    }

    static class Green extends Color {
        public Green() {
            type = 2;
            color = "绿色";
        }
    }

    static class ColorProducer {
        private final static Map<Integer, Color> cache = new HashMap<Integer, Color>(16);

        static {
            //初始化一些
            Red red = new Red();
            cache.put(red.getType(), red);

            Green green = new Green();
            cache.put(green.getType(), green);
        }

        public static Color getColor(Integer type) {
            if (null == type) {
                return null;
            }
            Color color = cache.get(type);
            if (null != color) {
                return (Color) color.clone();
            }

            return null;
        }
    }
}

下一篇:Java版本设计模式——行为型模式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值