Java 简单工厂类小🌰

package com.jasonote.interfaceStudy;

/**
 * Created by Jasonote on 2017/11/27.
 * 工厂模式设计
 */
public class FactoryInterface {
    public static void main(String[] args) {
        Fruit f = Factory.init(Apple.class);
        f.eat();

        Fruit o = Factory.init(Orange.class);
        o.eat();
    }
}

class Factory {
    public static Fruit init(Class<?> clazz) {
        if (clazz.getName().equals(Apple.class.getName())) {
            return new Apple();
        } else if (clazz.getName().equals(Orange.class.getName())) {
            return new Orange();
        }
        return null;
    }
}

interface Fruit {
    void eat();
}

class Apple implements Fruit {

    @Override
    public void eat() {
        System.out.println("其实我是一个苹果,你可以吃我");
    }
}

class Orange implements Fruit {

    @Override
    public void eat() {
        System.out.println("其实我是一个橘子,你不可以吃我");
    }
}



Jason.wang

When you find your talent can't afford to be ambitious, be quiet and study !

You may also like...