对设计模式—Abstract Factory模式的认识

本文通过一个生动的例子介绍了抽象工厂模式的应用。它展示了如何利用抽象工厂模式来创建一系列相关或相互依赖的对象,而无需指定它们具体的类。通过这个模式,客户端可以在不指定产品具体类型的情况下创建多个产品族中的产品对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现在公司搬家了,吃饭都成了问题,每次得跑到外面去吃,走到一个小吃店都不知道吃什么,只好点了个盖交饭.其实厨房就相当与Factory ,你想吃什么就给你炒什么.

public interface Vegetables
{
public void cooking();
}

public class MeatVegetables implements Vegetables
{
public void cooking()
{
System.out.println("Cooking Meat and Vegetables");
}
}

public class PastaVegetables implements Vegetables
{
public void cooking()
{
System.out.println("Cooking Pasta and Vegetables");
}
}

public interface Noodle
{
public void cooking();
}

public class MeatNoodle implements Noodle
{
public void cooking()
{
System.out.println("Meat and Noodle");
}
}

public class VegetablesNoodle implements Noodle
{
public void cooking()
{
System.out.println("Vegetables and Noodle");
}

}
public interface Buyer
{
//
public Vegetables buyVegetables(Vegetables whichVegetables);

public Noodle buyNoodle(Noodle whichNoodle);
}

public class WageWorker implements Buyer
{
public Vegetables buyVegetables(Vegetables whichVegetables)
{
return whichVegetables;
}

public Noodle buyNoodle(Noodle whichNoodle)
{
return whichNoodle;
}
}

public class TestVegetables
{
public static void main(String[]args)
{
//MeatVegetables Instance
Vegetables meatVegetables = new MeatVegetables();
//PastaVegetables Instance
Vegetables pastaVegetables = new PastaVegetables();
//MeatNoodle Instance
Noodle meatNoodle = new MeatNoodle();
//VegetablesNoodle Instance
Noodle vegetablesNoodle = new VegetablesNoodle();
//Custom Instance
Buyer custom = new WageWorker();
//Choice meatVegetables
custom.buyVegetables(meatVegetables ).cooking();
//Choice pastaVegetables
custom.buyVegetables(pastaVegetables).cooking();
//Choice meatNoodle
custom.buyNoodle(meatNoodle).cooking();
//Choice vegetablesNoodle
custom.buyNoodle(vegetablesNoodle).cooking();
}
}

抽象工厂:
1.抽象工厂模式可以向客户端提供一个接口,使得客户端在不必指定产品的具体类型的情况下,创建多个产品族中的产品对象。这就是抽象工厂模式的用意。
2.抽象工厂模式是所有形态的工厂模式中最为抽象和最具一般性的一种形态
3.我们还可以动态扩张其他类
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值