文章目录
0 设计模式
不了解设计模式的小伙伴可以通过这篇文章了解一下什么是设计模式
https://blog.csdn.net/qq_42874315/article/details/120006447?spm=1001.2014.3001.5502
1 享元模式
享元模式的核心思想就是:重复利用对象,将多个对象提前放入在池中,需要某个对象时不用new,直接去池中拿,用完了再放回来就好,效率很高,省去了创建对象的事件,连接池、线程池、常量池都是这个原理,Java中的String就是享元模式。
2 实现思路
2.1 享元模式
2.2 享元模式+组合模式
享元+组合是很好的搭配,但是难度很高,可以先去阅读一下组合模式
https://blog.csdn.net/qq_42874315/article/details/120295558
3 需要的类
- 接口
- 接口实现类
- 工厂(也可以使用一个简单类代替,只要里面池即可)
工厂中定义一个map属性,这个map就是存储实现类的池 - 测试类
通过工厂构造出实现类(在构造实现类的时候调用了池)
4 具体实现
4.1 Shape接口
/**
* @Author ChenJiahao(程序员五条)
* @Date 2021/9/13 20:40
*/
public interface Shape {
void draw();
}
4.2 Circle(接口实现类)
/**
* @Author ChenJiahao(程序员五条)
* @Date 2021/9/13 20:41
*/
public class Circle implements Shape {
private String color;
private int x;
private int y;
private int radius;
public Circle(String color, int x, int y, int radius) {
this.color = color;
this.x = x;
this.y = y;
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Circle: Draw() [Color : " + color + ", x : " + x +", y :" + y +", radius :" + radius);
}
}
4.3 ShapeFactory
circleMap属性就是池的概念
/**
* circleMap属性就是池的概念
* @Author ChenJiahao(程序员五条)
* @Date 2021/9/13 20:43
*/
public class ShapeFactory {
private static final Map<String, Shape> circleMap = new HashMap<>();
public static Shape getCircle(String color) {
Circle circle = (Circle)circleMap.get(color);
if(circle == null) {
circle = new Circle(color,10,20,30);
circleMap.put(color, circle);
System.out.println("Creating circle of color : " + color);
}
return circle;
}
}
4.4 测试类
/**
* @Author ChenJiahao(程序员五条)
* @Date 2021/9/13 20:44
*/
public class Test {
private static final String colors[] =
{ "Red", "Green", "Blue", "White", "Black" };
public static void main(String[] args) {
for(int i = 0; i < 5; ++i) {
Circle circle = (Circle)ShapeFactory.getCircle(colors[i]);
circle.draw();
}
}
}
5 思维导图
6 示例源码地址
https://github.com/ChenJiahao0205/design-pattern/tree/master
最后
我是通过马士兵老师的视频和菜鸟教程学习的,部分内容可能会有雷同
想阅读更多设计模式相关文章,欢迎到我的专栏【设计模式学习笔记】、【设计模式】中去查看
在23篇设计模式文章发布完成之后,我会公开完整的思维导图,点关注,不迷路
感谢大家看到这里,文章如有不足,欢迎大家指出;彦祖点个赞吧彦祖点个赞吧彦祖点个赞吧,欢迎关注程序员五条!