java 简单工厂&抽象工厂

工厂模式:就是提供一个实例化对象的接口,让子类去决定实现哪个具体对象

1:简单工厂

public abstract class Person {

}
public class XiaoLi extends Person {
public void eat() {
System.out.println("小李吃饭");
}
}
public class XiaoMing extends Person {
public void eat() {
System.out.println("小明吃饭");
}
}
/**
* 简单工厂
*/
public class SimpleFactory {
public Person instance(String username) {
if (username.equals("1")) {
return new XiaoMing();
} else if (username.equals("2")) {
return new XiaoLi();
}
return null;
}
}
public class SimpleTest {
public static void main(String[] args) {
SimpleFactory factory = new SimpleFactory();
Person xiaoming = factory.instance("1");
Person xiaoli = factory.instance("2");
XiaoLi m = (XiaoLi) xiaoli;
m.eat();
XiaoMing l = (XiaoMing) xiaoming;
l.eat();

}
}
--------------------------------------------------------------------------------------------------------
2:抽象工厂
public abstract class Product {
}
public class MobilePhone extends Product {
public void desc() {
System.out.println("this is mobilephone");
}
}
public class Pen extends Product {
public void desc(){
System.out.println("this is pen");
}
}
/**
* 抽象工厂-每个类别创建自己的工厂
*/
public abstract class Afactory {
public abstract Product instance();
}
public class MobilePhoneFactory extends  Afactory {
@Override
public Product instance() {
return new MobilePhone();
}
}
public class PenFactory extends Afactory {
@Override
public Product instance() {
return new Pen();
}
}
/**
* 抽象工厂模式测试
* 工厂模式:提供一个实例化对象的接口,让子类去决定实例那个具体对象
*/
public class TestAbs {
public static void main(String[] args) {
Afactory penFactory = new PenFactory();
Pen pen = (Pen) penFactory.instance();
pen.desc();
Afactory mobileFactory = new MobilePhoneFactory();
MobilePhone mobilePhone = (MobilePhone) mobileFactory.instance();
mobilePhone.desc();
}
}

转载于:https://www.cnblogs.com/coderdxj/p/9635023.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值