Java的设计模式 之 简单的工厂模式(二)

时间:2022-05-02 00:09:33

下面的代码是稍微改进后的工厂模式

    abstract class MoveAble{
    public abstract void run();
}
abstract class Woopen{
    public abstract void attack();
}

abstract class Food{
    public abstract void eat();
}

interface AllFactory{
    public MoveAble createM();
    
    public Woopen createW();
    
    public Food createF();
}

class Car extends MoveAble{
    public void run(){
        System.out.println("Car is runing");
    }
}

class AK47 extends Woopen{
    public void attack(){
        System.out.println("da da da");
    }
}

class Apple extends Food{
    public void eat(){
        System.out.println("Name");
    }
}

class Broom extends MoveAble{
    public void run(){
        System.out.println("flaying ....");
    }
}

class MagicStick extends Woopen{
    public void attack(){
        System.out.println("Bang ....");
    }
}

class MashRoom extends Food{
    public void eat(){
        System.out.println("Ya you du !!!");
    }
}

class DefaultFactory implements AllFactory{
    public MoveAble createM(){
        return new Car();
    }
    
    public Woopen createW(){
        return new AK47();
    }
    
    public Apple createF(){
        return new Apple();
    }
}

class MagicFactory implements AllFactory{
    public MoveAble createM(){
        return new Broom();
    }
    
    public Woopen createW(){
        return new MagicStick();
    }
    
    public Food createF(){
        return new MashRoom();
    }
}