静态工厂方法模式中,各种产品有公共的接口,通过调用工厂类中的同一个静态方法,只要传入不同的参数,就可以得到不同的产品。
package
staticfactorymethod;
/* 水果类的接口,声明了种植、生长和收获三个方法
*
*/
public interface Fruit {
void plant();
void grow();
void harvest();
}
/* 水果类的接口,声明了种植、生长和收获三个方法
*
*/
public interface Fruit {
void plant();
void grow();
void harvest();
}
package
staticfactorymethod;
public class Apple implements Fruit{
public void plant() {
}
public void grow() {
}
public void harvest() {
}
}
public class Apple implements Fruit{
public void plant() {
}
public void grow() {
}
public void harvest() {
}
}
package
staticfactorymethod;
public class Grape implements Fruit{
public void plant() {
}
public void grow() {
}
public void harvest() {
}
}
public class Grape implements Fruit{
public void plant() {
}
public void grow() {
}
public void harvest() {
}
}
package
staticfactorymethod;
public class Strawberry implements Fruit{
public void plant() {
}
public void grow() {
}
public void harvest() {
}
}
public class Strawberry implements Fruit{
public void plant() {
}
public void grow() {
}
public void harvest() {
}
}
package
staticfactorymethod;
public class FruitGardener {
public static Fruit factory (String name) throws BadFruitException {
if (name.equalsIgnoreCase( " apple " ))
return new Apple();
else if (name.equalsIgnoreCase( " grape " ))
return new Grape();
else if (name.equalsIgnoreCase( " strawberry " ))
return new Strawberry();
else
throw new BadFruitException( " no such fruit : " + name);
}
public static void main(String [] args) {
try {
System.out.println(FruitGardener.factory( " Apple " ));
System.out.println(FruitGardener.factory( " Grape " ));
System.out.println(FruitGardener.factory( " Strawberry " ));
System.out.println(FruitGardener.factory( " Banana " ));
} catch (BadFruitException bfe) {
System.out.println(bfe);
}
}
}
public class FruitGardener {
public static Fruit factory (String name) throws BadFruitException {
if (name.equalsIgnoreCase( " apple " ))
return new Apple();
else if (name.equalsIgnoreCase( " grape " ))
return new Grape();
else if (name.equalsIgnoreCase( " strawberry " ))
return new Strawberry();
else
throw new BadFruitException( " no such fruit : " + name);
}
public static void main(String [] args) {
try {
System.out.println(FruitGardener.factory( " Apple " ));
System.out.println(FruitGardener.factory( " Grape " ));
System.out.println(FruitGardener.factory( " Strawberry " ));
System.out.println(FruitGardener.factory( " Banana " ));
} catch (BadFruitException bfe) {
System.out.println(bfe);
}
}
}
package
staticfactorymethod;
public class BadFruitException extends Exception {
public BadFruitException (String msg) {
super (msg);
}
}
public class BadFruitException extends Exception {
public BadFruitException (String msg) {
super (msg);
}
}