被客户不断变化的需求“折磨”:
开发一个打印机控制程序,要能够实现开机,关机和打印功能
class Printer{
void open(){
System.out.println("Open");
}
void close(){
System.out.println("Close");
}
void print(String s){
System.out.println("print-->"+s);
}
}
class Test{
public static void main(String args[]){
Printer printer = new Printer();
Printer.open();
Printer.print("abc");
Printer.close();
}
}
办公室新加了一台打印机,控制两台打印机(不是同一个牌子)
class HPPrinter{
void open(){
System.out.println("Open");
}
void close(){
System.out.println("Close");
}
void print(String s){
System.out.println("print-->"+s);
}
}
class CanonPrinter extends Printer{
void open(){
System.out.println("Open");
}
void close(){
this.clean();
System.out.println("Close");
}
void print(String s){
System.out.println("print-->"+s);
}
void clean(){
System.out.println("clean”);
}
class Test{
public static void main(String args[]){
int flag = 0;//flag用于模拟用户的输入0或1;
if(flag == 0){
HPPrinter hpPrinter = new HPPrinter();
hpPRinter.open();
hpPRinter.print("abc");
hpPRinter.close();
}
else if(flag == 1){
CanonPrinter canonPrinter = new CannonPrinter();
CanonPrinter.open();
CanonPrinter.print("abc");
CanonPrinter.close();
}
}
}
大量的重复代码,修改如下:
class HPPrinter extends Printer{
}
class CanonPrinter extends Printer{
void close(){
this.clean();
super.close();//调用父类中的close代码
}
void clean(){
System.out.println("Close");
}
}
class Printer{
void open(){
System.out.println("Open");
}
void close(){
System.out.println("Close");
}
void print(String s){
System.out.println("print-->"+s);
}
}
}
class Test{
public static void main(String args[]){
int flag = 0;//flag用于模拟用户的输入0或1;
if(flag == 0){
HPPrinter hpPrinter = new HPPrinter();
hpPRinter.open();
hpPRinter.print("abc");
hpPRinter.close();
}
else if(flag == 1){
CanonPrinter canonPrinter = new CannonPrinter();
CanonPrinter.open();
CanonPrinter.print("abc");
CanonPrinter.close();
}
}
}
办公室新加了一台打印机,控制三台打印机(不是同一个牌子)
class HPPrinter extends Printer{
}
class CanonPrinter extends Printer{
void close(){
this.clean();
super.close();//调用父类中的close代码
}
void clean(){
System.out.println("Close");
}
}
class Printer{
void open(){
System.out.println("Open");
}
void close(){
System.out.println("Close");
}
void print(String s){
System.out.println("print-->"+s);
}
}
}
class ShenzhouPrinter extends Printer{
}
class Test{
public static void main(String args[]){
int flag = 0;//flag用于模拟用户的输入0或1;
if(flag == 0){
HPPrinter hpPrinter = new HPPrinter();
hpPRinter.open();
hpPRinter.print("abc");
hpPRinter.close();
}
else if(flag == 1){
CanonPrinter canonPrinter = new CannonPrinter();
CanonPrinter.open();
CanonPrinter.print("abc");
CanonPrinter.close();
}
}
}