抽象工厂

Abstract Factory 提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。

抽象工厂模式:

多个抽象产品类,每个抽象产品类可以派生出多个具体产品类  
一个抽象工厂类,可以派生出多个具体工厂类
每个具体工厂类可以创建多个具体产品类的实例


抽象工厂是应对产品族概念的。比如说,每个汽车公司可能要同时生产轿车,货车,客车,那么每一个工厂都要有创建轿车,货车和客车的方法。应对产品族概念而生,增加新的产品线很容易,但是无法增加新的产品。

15161319_gdTp.jpg

工厂接口

public interface IAnimalFactory {

    ICat createCat();
	
    IDog createDog();
}

实现工厂接口的两个工厂类

public class BlackAnimalFactory implements IAnimalFactory {

    public ICat createCat() {
        return new BlackCat();
    }

    public IDog createDog() {
        return new BlackDog();
    }

}
public class WhiteAnimalFactory implements IAnimalFactory {

    public ICat createCat() {
        return new WhiteCat();
    }

    public IDog createDog() {
        return new WhiteDog();
    }

}

两个动物接口

public interface ICat {

    void eat();
}
public interface IDog {

    void eat();
}

动物接口的实现

public class WhiteCat implements ICat {

    public void eat() {
        System.out.println("The white cat is eating!");
    }

}
public class BlackCat implements ICat {

    public void eat() {
        System.out.println("The black cat is eating!");
    }

}
public class BlackDog implements IDog {

    public void eat() {
        System.out.println("The black dog is eating");
    }

}
public class WhiteDog implements IDog {

    public void eat() {
        System.out.println("The white dog is eating!");
    }

}

client调用

public static void main(String[] args) {
    IAnimalFactory blackAnimalFactory = new BlackAnimalFactory();
    ICat blackCat = blackAnimalFactory.createCat();
    blackCat.eat();
    IDog blackDog = blackAnimalFactory.createDog();
    blackDog.eat();
    
    IAnimalFactory whiteAnimalFactory = new WhiteAnimalFactory();
    ICat whiteCat = whiteAnimalFactory.createCat();
    whiteCat.eat();
    IDog whiteDog = whiteAnimalFactory.createDog();
    whiteDog.eat();
}


参考:http://zhidao.baidu.com/link?url=U08vZ9S8nLfRy6pdVlVqqNA_3ZEMa-6UU8mBCzGhJZyb4oY2XyXZKlhnz2GlirR7oRfBRL_XB-26XA2cO0iRBK

http://blog.youkuaiyun.com/superbeck/article/details/4446177


转载于:https://my.oschina.net/hnuweiwei/blog/222722

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值