[BlankFox Study Notes - Refactoring and Patterns] Refactoring towards Factory - refactoring code for object creation

Refactoring towards Factory

Note version: 1.0
Author: BlankFox ( CSDN homepage )
Archive: Refactoring and Patterns

Written in front:

ps: Refactoring is the reconstruction of existing code, making it easier to understand, expand and modify. During the process of refactoring, the code cannot be modified by feeling, which will cause many problems-the code cannot run after refactoring, the code More complex, new parts of the code that need to be refactored. Therefore, code refactoring needs some method guidance for finding problems, as well as some general steps, step by step, and step-by-step testing.

ps: In the existing code, there must be a lot of object creation content. Excellent code will clearly tell the reader of the code - what object is created, instead of letting the reader understand the details of the constructor - if the code appears Many constructors with the same name - use refactoring to create method encapsulation, if multiple constructors appear so that the responsibility of the original class is unclear - use refactoring to extract the creation method wrapper into a simple factory, similar functions appear but with different creation Object methods - use refactoring to move towards factory methods

1. Code problem

First determine the problem, in order to know where can be optimized

Error example. 1 - too many constructors with the same name\color{red}{Error example.1 - too many constructors with the same name}Error example . 1 - too many constructors with the same name

//错误示例.1——太多的同名构造函数
/* 创建一个描述账单的类,该类有多个字段,多个构建函数对应不同的账单 */
class Bill{
    
    
    /* 全构造函数(包含所有参数) */
    public Bill(int id,String name,Type type,int money,Date date,String owner,...){
    
    ...}
    /* 构造一个普通账单,id以及date等都自动分配 */
    public Bill(String name,Type type,int money){
    
    ...}
    /* 构造一个特殊支出账单,表示该支出是持久的 */
    public Bill(String name,int money,Type specialType){
    
    }//这里故意将位置调整一下,模拟错误
    ...
    //more public Bill(){}
}

class Client{
    
    
    public void useBill(){
    
    
        /* 该怎么构建Bill呢? 这要求使用者熟悉Bill构建详细内容 */
        Bill bill=new Bill(???);
    }
}

This problem can be classified as difficult to understand the code, using simplified refactoring - the core idea is to make the code easier to understand and the structure more reasonable, one of the methods is to use the creation method to encapsulate the constructor with the same name - detailed example. 1 - — Encapsulation using the create method

Error example. 2 - creating too many responsibilities and scattered \color{red}{Error example.2 - creating too many responsibilities and scattered}Mistake Example . 2 - Create too many and scattered responsibilities

//错误示例.2——创建职责过多且分散
/* 稍微改进上一个错误示例,简单封装实现了自我工厂(自己负责自己创建) */
class Bill{
    
    
    /* 全构造函数(包含所有参数) */
   	private Bill(int id,String name,Type type,int money,Date date,String owner,...){
    
    ...}
    /* 构造一个普通账单,id以及date等都自动分配 */
    public static Bill defaultBill(String name,Type type,int money){
    
    ...}
    /* 构造一个特殊支出账单,表示该支出是持久的 */
   	public static Bill staticOutBill(String name,Type specialType,int money){
    
    }//这里故意将位置调整一下,模拟错误
    ...
    //more public static Bill XXXBill(){}——这里你可以创建一些Bill的子类实现更多的功能
}
/* 尽管现在我们将创建函数名称和创建出的Bill描述结合起来了,但是过多的创建函数占用了Bill太多内容,而且static函数?不是很有必要呆在Bill中,这不应该是它的责任 */

Too many creation responsibilities - making your class as strange as a banknote being responsible for printing different denominations by itself , it is easy to think of using a simple factory to be responsible for creating functions - see example.2 - using factories to centralize creation responsibilities

ErrorExample. 3 – Duplication of the same logic\color{red}{ErrorExample.3 – Duplication of the same logic}Error example . 3 - repetition of the same logic

//错误示例.3——相同逻辑的重复
class RootNodeTest{
    
    
    public void showRootTest(){
    
    
        /* 处理代码中创建部分不同之外,其余部分大致相同 */
        Node node=new Root();
        
        node.addChild("next1");
        node.addChild("next2");
        //do other sameWork
        
        node.show();//使用root的show测试结果
    }
}

class NomalNodeTest{
    
    
    public void showNodeTest(){
    
    
        
        Node node=new NomalNode();
        
        node.addChild("next1");
        node.addChild("next12");
        //do other sameWork
        
        node.show();//使用nomalNode的show测试
    }
}

Too much repetitive work makes code reusability not high, and increases the cost of understanding each part. You can use the Factory Method method to seek common ground while reserving differences , extract common parts to the parent class, and make subclasses implement specific creation methods

Two, the corresponding reconstruction method

Example.1 - "rename" the constructor with the same name using the create method\color{green}{Example.1 - "rename" the constructor with the same name using the create method}Example . 1 - " rename " the same- named constructor using the create method

//示例.1——使用创建方法“重命名”同名构造方法
/* 对于一个简单的类,多个同名的构造方法使得其使用不便,使用创建方法为构造函数加以描述 */
class Bill{
    
    
    private final int id;
    ...
    
    public static Bill creatBillByMoney(int i){
    
    
        /* 使用创建方法包装了很多默认构造选项,使得使用更方便,而且名字更具体 */
        return new Bill(getId(),"默认",TYPE.DEFAULT,getDate(),i);
    }
    
    public Bill(int id,String name,Type type,Date date,int money){
    
    ...}
    
    ...
}

class Client{
    
    
    public void use(){
    
    
        //Bill b=new Bill(getId(),"默认",TYPE.DEFAULT,getDate(),i);
        Bill b=creatBillByMoney(100);
    }
}

Example.2 - Create Responsibilities Using Simple Factory Uniform Objects\color{green}{Example.2 - Create Responsibilities Using Simple Factory Uniform Objects}Example . 2 - Creating Responsibilities Using Simple Factory Uniform Objects _

//示例.2——使用简单工厂统一对象创建职责
class BillFactory extend Factory{
    
    
    public Bill creatBillByMoney(...){
    
    ...};
    public Bill creatBillWithTag(...){
    
    ...};
    //...
    
    /* 封装一些细节处理方法帮助创建对象,这部分功能不应该在原类中提炼 */
    private boolean dealDetails(...){
    
    ...};
    //...
}

Example. 3 —— Use the factory method to extract the common code, keep the polymorphic creation\color{green}{Example.3——Use the factory method to extract the common code, keep the polymorphic creation}Example . 3 ——Using the factory method to extract common code , retaining polymorphic creation _

//示例.3——使用工厂方法提取共有代码,保留多态创建
abstract class NodeTest{
    
    
    public void showNodeTest(){
    
    
        
        Node node=creatNode();
        
        node.addChild("next1");
        node.addChild("next2");
        //do other sameWork
        
        node.show();//使用nomalNode的show测试
    }
    
    abstract Node creatNode();
}

/* 省去了重复写一大堆逻辑代码,只需要关注其不同的部分即可,下面两个类都相当于一个简单工厂类 */
class RootNodeTest extend NodeTest{
    
    
   	@Override
    public Node creatNode(){
    
    
        return new RootNode();
    }
}

class NomalNodeTest extend NodeTest{
    
    
    @Override
    public Node creatNode(){
    
    
        return new NomalNode();
    }
}


3. Refactoring icon

insert image description here

Refactoring steps:

  1. Find codes with unclear responsibilities of multiple constructors with the same name or long construction process
  2. Create a method to encapsulate the constructor and refine the same logic
  3. According to the needs (there are too many creation methods, the original class does not need to bear the responsibility of construction), extract a simple factory class
  4. If there are multiple factories, and part of the processing logic is the same, extract the factory method class

4. Problem review

1. Main application scenarios? \color{blue}{1. Main application scenarios? }1. Main application scenarios ? _

Answer: Focus on creating objects, if there are too many constructors with the same name, it is not conducive to use - use the creation function package, if the task responsibility is not created properly - use the factory class to centralize the creation responsibility, if the processing method of creating the object is repeated - extract the factory method class

2. Is refactoring necessary? \color{blue}{2. Do you need to refactor? }2. Do you definitely need to refactor ?

Answer: The purpose of refactoring is to simplify understanding and make the code easy to expand. If there is no need for expansion at all or the code size is small, for example, there is no need to wrap a factory class separately for a creation responsibility. But if you repeat the code, too much object creation makes your code bloated and difficult to understand-don't hesitate, start refactoring immediately, don't make the problem more and more

3. How does refactoring towards or implementing the Factory pattern help? \color{blue}{3. How does refactoring to trend or implement the Factory pattern help? }3. How does refactoring to trend or implement the Factory pattern help ? _ _ _ _ _ _

Answer: Make object construction easy to understand, and decoupling between construction and use (modifying the object creation process will not lead to a large number of changes to the code that uses the object); making the division of responsibilities more reasonable, and the banknotes will not be responsible for printing themselves; part of the solution is due to the construction of different objects code duplication problem

Welcome to follow me and encourage each other ⭐️

⭐️⭐️Code Fox⭐️⭐️Main
content:

  • Update algorithm solution , algorithm and data structure from time to time
  • From time to time, share chicken soup for the soul , see the miscellaneous talk column for details
  • At present, I am mainly learning Java advanced content (virtual machine, framework, etc.), as well as very important software engineering, refactoring and design patterns , etc. I will refine, summarize and share the knowledge points in the book

Guess you like

Origin blog.csdn.net/caqjeryy/article/details/124403529