一个接口或者抽象类
package Factory;
/**
* 接口是特殊的抽象类
* @author GL
*
*/
public interface Noodel {
void makeNoodel();
}
多个实现类
实现类一
package Factory;
/**
* 实现类实现接口
* @author GL
*
*/
public class ChenNoodel implements Noodel{
@Override
public void makeNoodel() {
// TODO Auto-generated method stub
System.out.println("抻面");
}
}
实现类二
package Factory;
public class LZNoodel implements Noodel{
@Override
public void makeNoodel() {
// TODO Auto-generated method stub
System.out.println("兰州拉面");
}
}
实现类三
package Factory;
public class SGNoodel implements Noodel{
@Override
public void makeNoodel() {
// TODO Auto-generated method stub
System.out.println("手擀面");
}
}
工厂(面馆)
package Factory;
/**
* 工厂模式
* 根据传入的参数选择最后的成品
* @author GL
*
*/
public class NoodelFactory {
public final static int lzNoodel = 1;
public final static int cNoodel = 2;
public final static int sgNoodel = 3;
public static Noodel makeNoodels(int type) {
Noodel noodel =null;
switch (type) {
case 1:
noodel = new LZNoodel();
break;
case 2:
noodel = new ChenNoodel();
break;
case 3:
noodel = new SGNoodel();
break;
}
return noodel;
}
}
测试类
package Factory;
public class Test {
public static void main(String[] args) {
/**
* 多态(左边可以是接口或者抽象类,右边是实现类)
* 左边相同,右边不同
* 结果看右边
*
* 静态方法,可以用类名.方法名调用,NoodelFactory.makeNoodels()
*/
Noodel makeNoodel = NoodelFactory.makeNoodels(NoodelFactory.lzNoodel);
makeNoodel.makeNoodel();
Noodel makeNoodel2 = NoodelFactory.makeNoodels(NoodelFactory.sgNoodel);
makeNoodel2.makeNoodel();
Noodel makeNoodel3 = NoodelFactory.makeNoodels(NoodelFactory.sgNoodel);
makeNoodel3.makeNoodel();
}
}