工厂方法模式分三中:简单工厂模式、工厂方法模式、抽象工厂模式
1、简单工厂模式:根据一个工厂类,里面加一些逻辑判断来实例化产品类,如:
产品类:
interface ICar{
void run();}public Class BMW implements ICar{
public void run(){
System.println("宝马跑100码");}}public Class LBJN implements ICar{
public void run(){
System.println("兰博基尼跑200码");}}
工厂类:
public Class CarFactory{
public ICar createCar(int case){
if(case == 100){
return new BMW();}if(case == 200){
return new LBJN();}}}
调用:
public Class Test{
//创建工厂实例对象CarFactory factory = new CarFactory();//获取产品并且执行方法factory.createCar(200).run();}
2、工厂方法模式:将工厂抽象化,创建产品由其子类决定:
产品类:
interface ICar{
void run();}public Class BMW implements ICar{
public void run(){
System.println("宝马跑100码");}}public Class LBJN implementsICar{
public void run(){
System.println("兰博基尼跑200码");}}
工厂类:
//抽象工厂interface ICarFactory{
ICar createCar();}//创建宝马的工厂public Class BMWFactory implements ICarFactory{
ICar createCar(){
return new BMW();}}//创建兰博基尼的工厂public Class LMJNFactory implements ICarFactory{
ICar createCar(){
return new LMJN();}}
调用:
public Class Test{
//创建抽象工厂实例对象指向宝马factoryICarFactory factory = new BMWFactory();//获取产品并且执行方法factory.createCar().run();}
3、抽象工厂模式:抽象工厂模式中产品可能会有多个,如果产品只有一个则退化到工厂方法模式
产品类:
//食品类产品族interface IFood{
void eat();}public Class SummerFood implements IFood{
void eat(){
}}public Class WinnerFood implements IFood{
void eat(){
}}//衣服类产品族interface ICloths{
void dress();}public Class SummerCloths implements ICloths{
void dress(){}}public Class WinnerCloths implements ICloths{
void dress(){}}
工厂类:
-
interface IFactory{
IFood createFood();ICloths createCloths();-
} -
Public Class SummerFactory(){
IFood createFood(){
return new SummerFood();}ICloths createCloths(){
return new SummerCloths();}}Public Class WinnerFactory(){
IFood createFood(){
return new WinnerFood();}ICloths createCloths(){
return new WinnerCloths();}}
转载于:https://www.cnblogs.com/guoliangxie/p/5283559.html
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/109119.html原文链接:https://javaforall.net
