Refactoring-Improving the Design of Existing Code——学习笔记(6)
Chapter 11 Dealing with Generalization
(1)Pull Up Field
Two subclasseshave the same field. Move the field to the superclass.
(2)Pull Up Method
You have methodswith identical results on subclasses. Move them to the superclass.
(3)Pull Up Constructor Body
You haveconstructors on subclasses with mostly identical bodies. Create a superclassconstructor; call this from the subclass methods.
class Manager extends Employee…
public Manager(string name,string id,int grade) {
_name=name;
_id=id;
_grade=grade;
}
重构后:
public Manager (string name,string id,int grade) {
super(name,id);
_grade = grade;
}
(4)Push Down Method
Behavior on asuperclass is relevant only for some of its subclasses. Move it to thosesubclasses.
(5)Push Down Field
A field is usedonly by some subclasses. Move the field to those subclasses.
(6)Extract Subclass
A class hasfeatures that are used only in some instances. Create a subclass for thatsubset of features.
(7)Extract Superclass
You have twoclasses with similar features. Create a superclass and move the common featuresto the superclass.
(8)Extract Interface
Several clientsuse the same subset of a class’s interface, or two classes have part of theirinterfaces in common. Extract the subset into an interface.
(9)Callapse Hierarchy
A superclass andsubclass are not very different. Merge them together.
(10)Form Template Method
You have twomethods in subclasses that perform similar steps in the same order, yet thesteps are different. Get the steps into methods with the same signature, sothat the original methods become the same. Then you can pull them up.
(11)Replace Inheritance with Delegation
A subclass usesonly part of a superclasses interface or does not want to inherit data. Createa field for the superclass, adjust methods to delegate to the superclass, andremove the subclassing.
(12)Replace Delegation with Inheritance
You’re usingdelegation and are often writing many simple delegations for the entireinterface. Make the delegation class a subclass of the delegate.