標籤:des style blog http io os 使用 java ar
情境:
你有一個類型碼,它會影響類的行為,但你無法通過繼承手法來消除它
,可以使用狀態物件取代類型碼
類圖:
修改前:
Student
/** * @file Student.java * * * @author wumingkun * @version 1.0.0 * @Description */package com.demo.refactor.state.before;/** * @author wumingkun * */public class Student {private int id;private String name;private int type;public static final int A =1;public static final int B =2;public Student(int id, String name, int type) {super();this.id = id;this.name = name;this.type = type;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getType() {return type;}public void setType(int type) {this.type = type;}}
修改後:
Student
/** * @file Student.java * * * @author wumingkun * @version 1.0.0 * @Description */package com.demo.refactor.state.after;/** * @author wumingkun * */public abstract class Student {private int id;private String name;public static final int A =1;public static final int B =2;private StudentType type ;public Student(int id, String name,StudentType type) {super();this.id = id;this.name = name;this.type=type;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getType() {return type.getType();}public void setType(int type) {//調用Factory 方法this.type = StudentType.create(type);}}
StudentType
package com.demo.refactor.state.after;public abstract class StudentType {public abstract int getType();public static StudentType create(int type){switch (type) {case Student.A:return new TypeA();case Student.B:return new TypeB();default:throw new IllegalArgumentException();}}}
TypeA
/** * * @author wumingkun * @version 1.0.0 * @Description */package com.demo.refactor.state.after;/** * @author wumingkun * */public class TypeA extends StudentType {/* (non-Javadoc) * @see com.refractor.subcode.after.StudentManagement#getType() */@Overridepublic int getType() {return Student.A;}@Overridepublic String toString() {return "TypeA [type=" + getType() + "]";}}
TypeB
</pre><pre name="code" class="java">/** * * @author wumingkun * @version 1.0.0 * @Description */package com.demo.refactor.state.after;/** * @author wumingkun * */public class TypeB extends StudentType {/* (non-Javadoc) * @see com.refractor.subcode.after.StudentManagement#getType() */@Overridepublic int getType() {return Student.B;}@Overridepublic String toString() {return "TypeB [type=" + getType() + "]";}}
重構之4.Replace Type Code with State/Strategy(以State/Strategy取代類型碼)