问题描述:

I always seem to fall back on the Factory Pattern/Inheritance for code reuse, and have been reading about composition over inheritance and do see the benefits of the loose coupling. You definitely get dependencies with inheritance. So I am trying to wrap my head around a pattern for "process" objects.

They all basically,

  • get their "environmental variables" from a database,
  • Get a list of files,
  • Process/convert each file (think convert XML to CSV), which entails

    • Reading the file, line by line
    • Writing a file into a another format, line by line
    • updating status (writing status to a database)

Get a list of files may mean get a list of files from a local directory, or get a list of files from a remote FTP site.

The thing that I'm struggling with, with compositoin is CODE REUSE. Using inheritance, if I had a Base Abstract Class, I could put my GetEnvironment, UpdateStatus, methods in the base class and the child classes would get them for free. How would I be able to get code reuse like this using composition? I could have helper classes, but I would essentially repeat the boilerplate use of these helper classes in each "process" class. I can work up some pseudo code if necessary.

网友答案:

Given the details in the question, I would have my solution as follows:

  • Environment
    • Domain object that holds the environment details.
  • EnvironmentDAO and DBEnvironmentDAO
    • The interface and the DB-backed implementation to build the Environment domain object.
  • AToBConverter
    • Takes a file and reference to the environment object
    • performs the transformation, writes to another file and updates the status in the DB
  • Launcher
    • Takes a list of files.
    • Retrieves the Environment from the database using the DAO.
    • Employs a scalable mechanim (like ExecutorService) to run the AToBConverters in parallel.
相关阅读:
Top