UML类图:

【JAVA设计模式】工厂方法模式

工厂接口类:

package com.jthao.design.des.factorymethod;

public interface IFactory {

	public LeiFeng createLeifeng();

}

具体工厂类A:

package com.jthao.design.des.factorymethod;

public class VolunteerFactory implements IFactory {

	@Override
	public Volunteer createLeifeng() {
		return new Volunteer();
	}

}

具体工厂类B:

package com.jthao.design.des.factorymethod;

public class UndergraduateFactory implements IFactory {

	@Override
	public Undergraduate createLeifeng() {
		return new Undergraduate();
	}

}

对象接口类:

package com.jthao.design.des.factorymethod;

public class LeiFeng {

	public void sweep() {
		System.out.println("扫地");
	}

	public void wash() {
		System.out.println("洗衣");
	}

	public void buyRice() {
		System.out.println("买米");
	}

}

具体对象A:

package com.jthao.design.des.factorymethod;

public class Volunteer extends LeiFeng {
	
	public void sweep() {
		System.out.println("志愿者扫地");
	}

	public void wash() {
		System.out.println("志愿者洗衣");
	}

	public void buyRice() {
		System.out.println("志愿者买米");
	}

}

具体对象B:

package com.jthao.design.des.factorymethod;

public class Undergraduate extends LeiFeng {

	public void sweep() {
		System.out.println("大学生扫地");
	}

	public void wash() {
		System.out.println("大学生洗衣");
	}

	public void buyRice() {
		System.out.println("大学生买米");
	}

}

测试类:

package com.jthao.design.des.factorymethod;

public class factorymethodTest {

	public static void main(String[] args) {
		IFactory factory = new UndergraduateFactory();
		LeiFeng leifeng = factory.createLeifeng();
		leifeng.sweep();

		IFactory factory2 = new VolunteerFactory();
		leifeng = factory2.createLeifeng();
		leifeng.buyRice();
		leifeng.wash();

	}

}

相关文章:

  • 2022-12-23
  • 2021-06-03
  • 2021-05-22
  • 2021-05-09
  • 2021-08-01
  • 2022-12-23
猜你喜欢
  • 2021-10-11
  • 2021-10-31
  • 2021-07-17
  • 2021-07-17
  • 2021-06-02
相关资源
相似解决方案