java工厂模式例子

//TV接口
public interface TV{
	public void play();
}

//TV工厂接口
public interface TVFactory{
	public TV productTV();
}

//HaierTV实现TV接口
public class HaierTV implements TV{
	public void play(){
		System.out.println("-----------HaierTV------------");
	}
}

//TclTV实现TV接口
public class TclTV implements TV{
	public void play(){
		System.out.println("-----------TclTV------------");
	}
}

//HaierTV工厂类 实现TV工厂接口
public class HaierTVFactory implements TVFactory{
	public TV productTV(){
		System.out.println("HaierTVFactory create HaierTV");
		return new HaierTV();
	}
}
//TclTV工厂类 实现TV工厂接口
public class TclTVFactory implements TVFactory{
	public TV productTV(){
		System.out.println("TclTVFactory create TclTV");
		return new TclTV();
	}
}

//客户端类
public class ClientFactory{
	public static void main(String[] args) {
		try{
			TV tv;
			TVFactory factory =new HaierTVFactory();
			tv = factory.productTV();
			tv.play();
			
			TV tv1;
			TVFactory factory1 =new TclTVFactory();
			tv1 = factory1.productTV();
			tv1.play();
		}
		catch(Exception e){
			System.out.println(e.getMessage());
		}
	}
}

结果:
HaierTVFactory create HaierTV
-----------HaierTV------------
TclTVFactory create TclTV
-----------TclTV------------



转载于:https://my.oschina.net/u/1401580/blog/225386

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值