java 简单工厂&抽象工厂
2024-10-07 11:48:32
工厂模式:就是提供一个实例化对象的接口,让子类去决定实现哪个具体对象
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();
}
}
最新文章
- 第24/24周 数据库维护(Database Maintenance)
- Android 中MyApplication
- php 二分查找
- android 百度地图定位功能实现
- pearl(二分查找,stl)
- 关于UIFont和计算字符串的高度和宽度
- VR虚拟现实技术在教育领域的前景展望
- ASP.NET Core 2.0 使用支付宝PC网站支付
- UltraEdit激活方法
- 分布式进阶(十二)Docker固定Container IP
- Android的内存分配与回收
- PHP信号管理
- [九省联考2018]秘密袭击coat
- mysql添加用户,授权,刷新权限
- 第三周博客之二---Oracle中的sql语句
- Foundry feats. MultiverseStudio
- noip第3课资料
- skynet inject address file.lua
- 利用委托机制处理.NET中的异常
- monkey测试入门1