package day4;
/**
* 定义电话的标准:能够发送短信
*/
interface ICellPhone
{
/**
* 发送短信
*/
void sendMsg();
}
class HTC implements ICellPhone
{
@Override
public void sendMsg() {
System.out.println("It's a HTC phone");
}
}
class HuaWei implements ICellPhone
{
@Override
public void sendMsg() {
System.out.println("It's a HuaWei phone");
}
}
/**
* 电话工厂:用于屏蔽子类之间实现的差异
*/
class PhoneFactory
{
public static ICellPhone getInstance(String type)
{
ICellPhone p = null;
if("HTC".equals(type)){
p = new HTC();
}
else if("HuaWei".equals(type)){
p = new HuaWei();
}
return p;
}
}
public class SimpleFactoryDemo {
public static void main(String[] args) {
ICellPhone phone = new HTC();
phone.sendMsg();
phone = PhoneFactory.getInstance("HuaWei");
phone.sendMsg();
}
}
Java基础复习:简单工厂模式
最新推荐文章于 2023-12-27 09:56:38 发布