记录一下本身懂得的一些 设计模式 ,并尽量应用表达清跋扈的例子进行讲解。
享元模式
- Query simpleQuery = new SimpleQuery();
- System.out.println(simpleQuery.query("select * from t_student") == simpleQuery.query("select * from t_student")); // false
- Query cacheQuery = new CacheQuery(simpleQuery);
- System.out.println(cacheQuery.query("select * from t_student") == cacheQuery.query("select * from t_student")); // true
策略模式
策略模式应当是最基本的一个设计模式,它是对行动的一个抽象。jdk中的Comparator比较器就是一个应用策略设计模式的策略。
工厂模式
工厂模式的意义在于对象的创建、治理可以应用工厂去治理,而不是创建者自身。最典范的工厂模式应用者就是Spring,Spring内部的容器就是一个工厂,所有的bean都由这个容器治理,包含它们的创建、烧毁、注入都被这个容器治理。
工厂模式分简单工厂和抽象工厂。它们的差别在于抽象工厂抽象程度更高,把工厂也抽象成了一个接口,如许可以再每添加一个新的对象的时刻而不须要修改工厂的代码。
比如有个Repository接口,用于存储数据,有DatabaseRepository,CacheRepository,FileRepository分别在数据库,缓存,文件中存储数据,定义如下:
- public interface Repository {
- void save(Object obj);
- }
- class DatabaseRepository implements Repository {
- @Override
- public void save(Object obj) {
- System.out.println("save in database");
- }
- }
- class CacheRepository implements Repository {
- @Override
- public void save(Object obj) {
- System.out.println("save in cache");
- }
- }
- class FileRepository implements Repository {
- @Override
- public void save(Object obj) {
- System.out.println("save in file");
- }
- }
- public class RepositoryFactory {
- public Repository create(String type) {
- Repository repository =
推荐阅读
自负年夜 Google 的人工智能 AlphaGO 成为围棋界的百胜将近开端,AI(Artificial Intelligence,人工智能)这两个英文字,刹那间成为科技业最热点的关键字之一。而就在2017岁首?年代,早在>>>详细阅读
本文标题:记录自己理解的一些设计模式
地址:http://www.17bianji.com/lsqh/34663.html
1/2 1