Replace Type Code with Subclasses(以子类取代类型码)
生活随笔
收集整理的這篇文章主要介紹了
Replace Type Code with Subclasses(以子类取代类型码)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
有一個(gè)不可變的類型碼,它會(huì)影響類的行為
public class Employee {static final int ENGINNER = 0;static final int SALESMAN = 1;static final int MANAGER = 2;private int type;public Employee(int type) {this.type = type;}public int getType() {return type;} }重構(gòu):以子類取代類型碼
public class Employee {static final int ENGINNER = 0;static final int SALESMAN = 1;static final int MANAGER = 2;private int type;public Employee(int type) {this.type = type;}public static Employee create(int type) {switch(type) {case ENGINNER: return new Engineer();case SALESMAN: return new Salesman();case MANAGER: return new Manager();default:throw new IllegalArgumentException("Incorrect type code value.");}}public abstract int getType(); }public class Engineer extends Employee {public int getType() {return Employee.ENGINNER;} }總結(jié)
以上是生活随笔為你收集整理的Replace Type Code with Subclasses(以子类取代类型码)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: #1130 - Host 'localh
- 下一篇: JNDI配置原理详解