Definition:One Class has one responsibility
Best Implement:
/**
*
*/
package com.sean.designpattern.responsibility.onetask;
/**
* @author Sean_Zhang
*
*/
public interface Breathe {
public BreatheType breathe(String name);
}
/**
*
*/
package com.sean.designpattern.responsibility.onetask;
/**
* @author Sean_Zhang
*
*/
public class AirBreathe implements Breathe {
public BreatheType breathe(String name) {
System.out.println(name + " breathe " + BreatheType.AIR_BREATHE.getName());
return BreatheType.AIR_BREATHE;
}
}
/**
*
*/
package com.sean.designpattern.responsibility.onetask;
/**
* @author Sean_Zhang
*
*/
public class WaterBreathe implements Breathe {
/* (non-Javadoc)
* @see com.sean.designpattern.responsibility.onetask.Breathe#breathe(java.lang.String)
*/
public BreatheType breathe(String name) {
System.out.println(name + " breathe " + BreatheType.WATER_BREATHE.getName());
return BreatheType.WATER_BREATHE;
}
}
Better Implement:
/**
*
*/
package com.sean.designpattern.responsibility.onetask;
/**
* @author Sean_Zhang
*
*/
public class GoodBreathe {
public BreatheType getAirBreathe(String name) {
System.out.println(name + " breathe " + BreatheType.AIR_BREATHE.getName());
return BreatheType.AIR_BREATHE;
}
public BreatheType getWaterBreathe(String name) {
System.out.println(name + " breathe " + BreatheType.WATER_BREATHE.getName());
return BreatheType.WATER_BREATHE;
}
}
Bad Implement:
/**
*
*/
package com.sean.designpattern.responsibility.onetask;
/**
* @author Sean_Zhang
*
*/
public class BadBreathe {
public BreatheType getBreathe(String name) {
BreatheType type = null;
if("fish".equals(name)) {
type = BreatheType.WATER_BREATHE;
} else if("pig".equals(name)) {
type = BreatheType.AIR_BREATHE;
}
if(type != null) {
System.out.println(name + " breathe " + type.getName());
}
return type;
}
}