工厂方法模式,定义一个用于创建对象的接口,让子类决定实例化哪个类,工厂方法使一个类的实例化延迟到其子类
package com.yl.design;
public interface FruitApi {
public void eat();
}
package com.yl.design;
public class AppleApi implements FruitApi {
@Override
public void eat() {
System.out.println("eat apple...");
}
}
package com.yl.design;
public class PeachApi implements FruitApi {
@Override
public void eat() {
System.out.println("eat peach...");
}
}
package com.yl.design;
public abstract class Fruit {
protected abstract FruitApi factoryMethod();
public void eat() {
FruitApi fruitApi = factoryMethod();
fruitApi.eat();
}
}
package com.yl.design;
public class AppleObj extends Fruit {
@Override
protected FruitApi factoryMethod() {
return new AppleApi();
}
}
package com.yl.design;
public class PeachObj extends Fruit {
@Override
protected FruitApi factoryMethod() {
return new PeachApi();
}
}
package com.yl.design;
public class Test {
public static void main(String[] args) {
Fruit fruit = new AppleObj();
fruit.eat();
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_41359273/article/details/123357497
内容来源于网络,如有侵权,请联系作者删除!