Search code examples
javadesign-patternsrefactoringumlfacade

choosing the right pattern for object composite


There is a class named "Bill". Bill can be either "Electricity" , "Food" or "Customer" which are all POJO. So it contains three objects:

    public class Bill{
      private Electricity el1;
      private Food el2;
      private Customer el3;
      //setters and getters
      public setElectricity(...)
      ...
    }

List of Bills are populated using some DTOs. And each time, I need to check all elements to be sure what type of bill am I having.

My goal is to refactor this design.

I could also have one object and set the content regarding to the type, but is it having any standard pattern?

Is there any pattern for classes who can be a class based on the type that is requested? I mean Bill will be either electricity, food or customer regarding to the populating time.

Note: My application favored composition over inheritance It is also a “design by contract” based application.

Edit: Bill is not an abstract of it's objects. Lets assume, food is just specification of food like color and receipt! A bill can be one and only one of the object at a point of time.


Solution

  • If ElectricityBill, FoodBill, GasBill has some common functionality, then create Bill as abstract class and extend other classes from bill.

    If they have altogether different behaviour and state (which i doubt)then create Bill as interface and let other concrete class implement them.

    i usually call it simple factory pattern(dont confuse it with factory method/abstract factory pattern)

    public class BillFactory
    {
        Bill createBill(String type)
        {
             if(type.equals("Electricity"))
               {
                bill=new ElectricityBill();
           }
            ........
    
    
        }
    }