[设计模式]3.1简单工厂模式

一、卖票案例

//测试
public class CilentTest {
	public static void main(String arg[]){
		Customer p1=new Children();
		System.out.println(p1.calculate(100.00));		
		Customer p3=new Vip();
		System.out.println(p3.calculate(100.00));
	}
}
//
interface Customer {
	public double calculate(double price);
}
//vip票
class Vip implements Customer {
    private String name="VIP";
    private double jifeng=0;
    
	public double calculate(double price){	
		jifeng=jifeng+0.1*price;	
		System.out.println("Welcome VIP,Now your jifen is "+jifeng);	
		System.out.print(name+"'s price is ");	
		return 0.8*price;
	}	
}
//儿童票
class Children implements Customer{
	private String name="children";
	public double calculate(double price){	
		System.out.print(name+"'s price is ");
		return 0.5*price;
	}
}
//学生票
class Student implements Customer{
	private String name="student";	
	public double calculate(double price){		
		System.out.print(name+"'s price is ");		
		return 0.8*price;
	}
}

二、简单工厂模式

1、工厂模式的定义

定义一个创建产品对象的工厂接口,将产品对象的实际创建工作推迟到具体子工厂类当中。这满足创建型模式中所要求的“创建与使用相分离”的特点。在简单工厂模式中创建实例的方法通常为静态方法,因此简单工厂模式又叫作静态工厂方法模式

2、简单工厂模式的主要角色

  • 简单工厂(SimpleFactory):是简单工厂模式的核心,负责实现创建所有实例的内部逻辑。工厂类的创建产品类的方法可以被外界直接调用,创建所需的产品对象。
  • 抽象产品(Product):是简单工厂创建的所有对象的父类,负责描述所有实例共有的公共接口。
  • 具体产品(ConcreteProduct):是简单工厂模式的创建目标。

3、该模式的代码

//测试
public class CilentTest {
    public static  void  main(String[] args){
        Fruit fruit=FruitFarm.getFruit("apple");
        fruit.eat();

        Fruit fruit1=FruitFarm.getFruit("orange");
        fruit1.eat();
    }
}
//抽象产品
interface Fruit {
    public void eat();
}
//具体产品1:Apple
class Apple implements Fruit{
    @Override
    public void eat(){
        System.out.println("eat Apple!");
    }
}
//具体产品2:Orange
class Orange implements Fruit{
    @Override
    public void eat() {
        System.out.println("eat Orange!");
    }
}
//SimpleFactory工厂
class FruitFarm {
    public static Fruit getFruit(String args){
        if(args.equalsIgnoreCase("apple")){
            return new Apple();
        }else if(args.equalsIgnoreCase("orange")){
            return new Orange();
        }else{
            return null;
        }
    }
}

优点:
1、一个调用者想创建一个对象,只要知道其名称就可以了。
2、扩展性高,如果想增加一个产品,只要扩展一个工厂类就可以。
3、屏蔽产品的具体实现,调用者只关心产品的接口。

缺点:
每次增加一个产品时,都需要增加一个具体类和对象实现工厂,
使得系统中类的个数成倍增加,在一定程度上增加了系统的复杂度,
同时也增加了系统具体类的依赖。这并不是什么好事。

使用场景:
1、日志记录器:记录可能记录到本地硬盘、系统事件、远程服务器等,用户可以选择记录日志到什么地方。
2、数据库访问,当用户不知道最后系统采用哪一类数据库,以及数据库可能有变化时。

https://www.runoob.com/design-pattern/factory-pattern.html

posted @ 2021-05-18 00:00  yu10001  阅读(64)  评论(0编辑  收藏  举报