一, 工厂模式(Factory Pattern)
定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类,工厂模式使其创建过程延迟到子类进行。
案例:
1, 接口
public interface Fruit {
String price();
}
2,三个实现类
public class Apple implements Fruit {
@Override
public String price() {
return "苹果:10元/斤";
}
}
public class Banana implements Fruit {
@Override
public String price() {
return "香蕉:20元/斤";
}
}
public class Pear implements Fruit {
@Override
public String price() {
return "梨: 5元/斤";
}
}
3,工厂类 根据参数名创建对象
public class FruitFactory {
public Fruit getFruit(String name) {
if (StringUtils.equals(name, "apple")) {
return new Apple();
} else if (StringUtils.equals(name, "banana")) {
return new Banana();
} else if (StringUtils.equals(name, "pear")) {
return new Pear();
} else {
return null;
}
}
}
4,测试
public class Demo {
public static void main(String[] args) {
FruitFactory factory = new FruitFactory();
// 苹果
Fruit apple = factory.getFruit("apple");
System.out.println(apple.price());
// 香蕉
Fruit banana = factory.getFruit("banana");
System.out.println(banana.price());
// 梨
Fruit pear = factory.getFruit("pear");
System.out.println(pear.price());
}
}
打印结果:
苹果:10元/斤
香蕉:20元/斤
梨: 5元/斤
二, 抽象工厂模式(Abstract Factory Pattern)
抽象工厂模式(Abstract Factory Pattern)是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂
案例:
1, 图形的接口, 实现类
public interface Shape {
void draw();
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("画一个圈");
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("画一个方形");
}
}
2, 颜色的接口, 实现类
public interface Color {
void fill();
}
public class Red implements Color {
@Override
public void fill() {
System.out.println("填充了红色");
}
}
public class Green implements Color {
@Override
public void fill() {
System.out.println("填充了绿色");
}
}
3, 抽象工厂, 工厂提供者, 颜色工厂, 图形工厂
public abstract class AbstractFactory {
public abstract Shape getShape(String name);
public abstract Color getColor(String name);
}
public class FactoryProducer {
public AbstractFactory getFactory(String factoryName){
if(StringUtils.equals(factoryName, "color")) {
// 颜色工厂
return new ColorFactory();
} else if(StringUtils.equals(factoryName, "shape")) {
// 图形工厂
return new ShapeFactory();
}
return null;
}
}
public class ColorFactory extends AbstractFactory {
@Override
public Shape getShape(String name) {
return null;
}
@Override
public Color getColor(String name) {
if (StringUtils.equals(name, "red")) {
return new Red();
} else if (StringUtils.equals(name, "green")) {
return new Green();
}
return null;
}
}
public class ShapeFactory extends AbstractFactory {
@Override
public Shape getShape(String name) {
if (StringUtils.equals(name, "circle")) {
return new Circle();
} else if (StringUtils.equals(name, "square")) {
return new Square();
}
return null;
}
@Override
public Color getColor(String name) {
return null;
}
}
4, demo
public static void main(String[] args) {
FactoryProducer producer = new FactoryProducer();
// 画图形
AbstractFactory shapeFactory = producer.getFactory("shape");
Shape circle = shapeFactory.getShape("circle");
circle.draw();
Shape square = shapeFactory.getShape("square");
square.draw();
// 填充颜色
AbstractFactory colorFactory = producer.getFactory("color");
Color red = colorFactory.getColor("red");
red.fill();
Color green = colorFactory.getColor("green");
green.fill();
}
打印结果:
画一个圈
画一个方形
填充了红色
填充了绿色
三, 单例模式(Singleton Pattern)
这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
案例:
1, 饿汉式
public class SingleObject {
// 全局就一个对象
private static SingleObject instance = new SingleObject();
// 私有化构造器, 外界不能new对象
private SingleObject(){}
// 获取对象
public static SingleObject getInstance(){
return instance;
}
}
2, 懒汉式 (延迟加载)
public class SingleObjectB {
// 全局就一个对象
private static SingleObjectB instance = null;
// 私有化构造器, 外界不能new对象
private SingleObjectB(){}
// 获取对象
public static SingleObjectB getInstance(){
// 此处需要双重判断,防止多次创建对象
if (null == instance) {
synchronized (SingleObjectB.class) {
if (null == instance) {
instance = new SingleObjectB();
}
}
}
return instance;
}
}
3, 静态内部类(申明式)
public class SingleObjectC {
// 内部类
private static class SingleHolder{
private static final SingleObjectC singleObjectC = new SingleObjectC();
}
private SingleObjectC(){}
public static SingleObjectC getInstance(){
return SingleHolder.singleObjectC;
}
}
4, 枚举(实现单例模式的最佳方法)
public class SingleObjectD {
private SingleObjectD(){}
public static SingleObjectD getInstance(){
return SingleEnum.INSTENCE.getInstence();
}
private enum SingleEnum{
INSTENCE,
;
private SingleObjectD singleObjectD;
// JVM保证此方法只执行一次
SingleEnum(){
singleObjectD = new SingleObjectD();
}
private SingleObjectD getInstence(){
return singleObjectD;
}
}
}
四, 建造者模式(Builder Pattern)
使用多个简单的对象一步一步构建成一个复杂的对象。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。如StringBuilder
案例: 如肯德基套餐, 食物不变, 可以有多种组合
食物接口:
public interface Item {
// 食物名
String name();
// 食物价格
float price();
// 包装类型
Packing pack();
}
包装类型:
public interface Packing {
// 包装
String name();
}
public class Wrapper implements Packing {
@Override
public String name() {
return "纸包装";
}
}
public class Bottle implements Packing {
@Override
public String name() {
return "瓶子包装";
}
}
汉堡类型:
public abstract class Burger implements Item {
@Override
public Packing pack() {
// 所有汉堡都是纸包装的
return new Wrapper();
}
}
public class VegBurger extends Burger {
@Override
public String name() {
return "蔬菜汉堡";
}
@Override
public float price() {
return 20.0f;
}
}
public class ChickenBurger extends Burger {
@Override
public String name() {
return "鸡肉汉堡";
}
@Override
public float price() {
return 12.0f;
}
}
饮料类型:
public abstract class Drink implements Item {
@Override
public Packing pack() {
// 所有饮料都是瓶子包装的
return new Bottle();
}
}
public class Milk extends Drink {
@Override
public String name() {
return "牛奶";
}
@Override
public float price() {
return 8.0f;
}
}
public class Coke extends Drink {
@Override
public String name() {
return "可乐";
}
@Override
public float price() {
return 5.0f;
}
}
套餐:
public class Meal {
private List<Item> meal = new ArrayList<>(8);
public void addItem(Item item) {
meal.add(item);
}
public float getPrice(){
float price = 0f;
for (Item item : meal) {
price += item.price();
}
return price;
}
public void showItems(){
for (Item item : meal) {
System.out.println("食物:" + item.name() + " 包装:" + item.pack().name() + " 价格:" + item.price());
}
System.out.println("总价:" + getPrice());
}
}
套餐建造者
public class MealBuilder {
public Meal buildVegMeal(){
Meal meal = new Meal();
meal.addItem(new VegBurger());
meal.addItem(new Milk());
return meal;
}
public Meal buildChickenMeal(){
Meal meal = new Meal();
meal.addItem(new ChickenBurger());
meal.addItem(new Coke());
return meal;
}
}
Demo
public static void main(String[] args) {
MealBuilder builder = new MealBuilder();
// 蔬菜套餐
Meal meal = builder.buildVegMeal();
meal.showItems();
// 鸡肉套餐
Meal meal2 = builder.buildChickenMeal();
meal2.showItems();
}
五, 原型模式(Prototype Pattern)
原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。
图形类:
public abstract class Shap implements Cloneable{
protected String name;
abstract void draw();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
protected Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
}
public class Square extends Shap {
public Square(){
name = "方形";
}
@Override
void draw() {
System.out.println("画一个正方形");
}
}
缓存
public class ShapCache {
private HashMap<String, Shap> cache = new HashMap<String, Shap>();
public void loadCache(){
Square square = new Square();
cache.put("square", square);
}
public Shap getShap(String key){
return (Shap)cache.get(key).clone();
}
}
Demo
public static void main(String[] args) {
ShapCache cache = new ShapCache();
cache.loadCache();
Shap square = cache.getShap("square");
square.draw();
// 方形
System.out.println(square.getName());
square.setName("haahha");
// haahha
System.out.println(square.getName());
Shap square2 = cache.getShap("square");
// 方形
System.out.println(square2.getName());
}
注意, 使用clone方法拷贝对象为浅拷贝, 根据需要做深拷贝处理.