工厂方法模式

x33g5p2x  于2022-03-08 转载在 其他  
字(0.9k)|赞(0)|评价(0)|浏览(229)

1.概念

工厂方法模式,定义一个用于创建对象的接口,让子类决定实例化哪个类,工厂方法使一个类的实例化延迟到其子类

2.简单案例

1.api接口

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...");
    }
}

2.抽象类

package com.yl.design;

public abstract class Fruit {

    protected abstract FruitApi factoryMethod();

    public void eat() {
        FruitApi fruitApi = factoryMethod();
        fruitApi.eat();
    }
}

3.抽象类的子类

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();
    }
}

4.测试

package com.yl.design;

public class Test {
    public static void main(String[] args) {
        Fruit fruit = new AppleObj();
        fruit.eat();
    }
}

相关文章