Refactor to use factory pattern