转载请注明出处
工厂方法设计模式是生成遵循某个接口的对象的典型方式。
理论上,通过这种方式,代码可以完全的与接口的实现分离。我们创建这种额外级别的间接性的一个很常见的原因是想要创建框架。
下面一个例子说明工厂方法的使用:
package newP;
/**
* Created by yangyiqing on 2017/8/3.
*/
interface Cycle{
void ride();
}
interface CycleFactory{
Cycle getCycle();
}
class Students implements Cycle{
private int StuNumber = 4;
@Override
public void ride() {
System.out.println(StuNumber +" Students ride Cycle");
}
public void eat(){
System.out.println("Students eat food");
}
}
class StudentsFactory implements CycleFactory{
@Override
public Cycle getCycle() {
return new Students();
}
}
class Teachers implements Cycle{
private int TeaNumber = 3;
@Override
public void ride() {
System.out.println(TeaNumber+ " Teachers ride Cycle");
}
public void run(){
System.out.println("Teachers run");
}
}
class TeachersFactory implements CycleFactory{
@Override
public Cycle getCycle() {
return new Teachers();
}
}
public class Ride {
public static void PersonRide(CycleFactory cyc){
Cycle c = cyc.getCycle();
c.ride();
// c.eat();
// c.run();
}
public static void main(String args[]){
PersonRide(new StudentsFactory());
PersonRide(new TeachersFactory());
}
}
以代码中的Students为例,静态方法PersonRide的参数为接口CycleFactory,其在main函数中接收的实参为New StudentsFactory(实现了CycleFactory),在这里‘实现了接口的类’向上转型为CycleFactory类型,此时只保留接口中的getCycle方法。
Cycle c = cyc.getCycle();
调用了转型完毕的StudentsFactory的getCycle方法,返回一个Students对象,而接收该Students对象的对象变量类型为Cycle,这当然是没问题的,因为Students已经实现了Cycle接口,所以Students对象向上转型为Cycle类型。
这也就是Students类中的eat()方法和Teachers类中的run方法无法被c调用的原因,因为他们在向上转型中丢失了。
--------
为验证上述结论,将c进行‘向下转型’,发现Students丢失的eat()方法回来了,(同样的操作也适用于Teachers,在这里只修改Students):
public class Ride {
public static void PersonRide(CycleFactory cyc){
Cycle c = cyc.getCycle();
c.ride();
Students s = (Students)c;
s.eat();
// c.eat();
// c.run();
}
public static void main(String args[]){
PersonRide(new StudentsFactory());
// PersonRide(new TeachersFactory());
}
}