Refactor code to use factory for