Skip to content

Design Patterns

Brandon C edited this page Nov 16, 2024 · 39 revisions

Strategy Pattern

The Strategy pattern is a behavioral design pattern for selecting an algorithm's behavior at runtime by defining a family of algorithms and making them interchangeable by encapsulation, allowing the algorithm to vary independently from the clients that use them. The pattern is used to load the mark scheme weightings from a mark_scheme.yaml file by allowing for multiple ways to load the weightings.

Abstraction: The MarkSchemeLoaderStrategy interface defines a loadWeightings() method for loading mark scheme weightings from mark_scheme.yaml into a Map<String, Map<String ,Integer>>. Any class that loads weightings must implement this interface and conform to the return type specified by the interface.

public interface MarkSchemeLoaderStrategy {
    public abstract Map<String, Map<String, Integer>> loadWeightings();
}

Realization: MarkSchemeLoader is a realization of the interface and provides the specific logic for loading mark scheme weightings, loading marks into the Map<String, Map<String, Integer>> variable using the Yaml utility class.

public class MarkSchemeLoader implements MarkSchemeLoaderStrategy {
    public Map<String, Map<String, Integer>> loadWeightings() {
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(Constants.MARK_SCHEME)) {
            if (inputStream == null) {
                throw new IllegalStateException("Could not find mark scheme resource: " + Constants.MARK_SCHEME);
            }
            return new Yaml().loadAs(inputStream);
        } catch (Exception e) {
            throw new IllegalStateException("Failed to load mark scheme weightings", e);
        }
    }
}

Command Pattern

The Command pattern is a behavioral design pattern that turns a request into an object containing all request details, allowing for parameterization of the request. The pattern is used for the compilation of Java source files. The compiling of each file is a request made.

Abstraction: The CompileCommand interface specifies the compile() method, which returns a boolean indicating success(true) or failure(false). The specific compilation details are abstracted, allowing for different implementations of compiling a Java source file.

public interface CompileCommand {
    public abstract boolean compile();
}

Realization: The JavaCompileCommand class is a realization of the interface and provides the specific logic for compiling Java source files in a directory. The class first validates if the compiler is available and obtains the system's Java compiler using ToolProvider.getSystemJavaCompiler(). The submission directory is scanned for .java files, where the class performs essential validation to ensure both the directory exists and contains valid Java source files. If any of these conditions fail, the compilation process is halted early.

Once the source files are identified, all Java files in the directory are wrapped into a collection for batch processing. The class prepares the compilation environment by setting up the classpath to point to the submission directory and bundles all discovered Java files together into the compiler arguments. The actual compilation is executed using the Java compiler's run method, which processes all source files in a single operation. The compilation is considered successful only if the compiler returns an exit code of zero, indicating no errors were encountered during the process.

This implementation demonstrates how the Command Pattern can encapsulate complex compilation logic while maintaining a simple interface. The class handles all the necessary details of file discovery, validation, and compilation while adhering to the single responsibility principle by focusing solely on Java compilation tasks.

public class JavaCompileCommand implements CompileCommand {
    @Override
    public boolean compile() {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null)
            return false;

        File directory = new File(submissionDirectory);
        List<String> javaFiles = new ArrayList<>();

        if (!directory.exists() || !directory.isDirectory())
            return false;
        for (File file : directory.listFiles())
            if (file.isFile() && file.getName().endsWith(".java"))
                javaFiles.add(file.getPath());

        if (javaFiles.isEmpty()) {
            System.out.println("No Java source files found for compilation.");
            return false;
        }

        List<String> compilerArgs = new ArrayList<String>();
        compilerArgs.add("-classpath");
        compilerArgs.add(submissionDirectory);
        compilerArgs.addAll(javaFiles);
        String[] argsArray = compilerArgs.toArray(new String[0]);
        int compilationResult = compiler.run(null, null, null, argsArray);
        return compilationResult == 0;
    }
}

Facade Pattern

The Facade Pattern is a structural design pattern that provides a simplified, high-level interface to complex subsystems, enhancing code readability and maintainability. It promotes loose coupling by hiding internal complexities, making subsystems easier to use such as simplifying the grading of student submissions.

Abstraction: The Facade interface specifies the processSubmissions() method which accepts a String parameter named zipFilePath. Realizations which process the submissions must implement this method and provide the submission zip file path.

public interface Facade {
    public void processSubmissions(String zipFilePath);
}

Realization: The GradingFacade provides a streamlined interface for processing student submissions. Its processSubmissions(String zipFilePath) method handles the entire workflow, starting with SubmissionExtractor.extractSubmissions(zipFilePath), which extracts submissions.zip into an output directory. Each student’s submission is organized into separate directories, with paths returned for further processing.

For each submission, the studentSubmission singleton instance is reset, and all tests within the submission's test suite are executed. Based on test results, grade items are generated, student information is gathered, and an AssignmentDetails instance is created to hold both student details and their corresponding grades.

Finally, the results are printed to the terminal using the toString() method of AssignmentDetails, and a PDF report is generated with result.generate(), which takes the AssignmentDetails instance as a parameter.

public class GradingFacade implements Facade {
    private final AbstractGradeFactory gradeFactory = new GradeFactory();
    private final PDF pdf = new PDFGenerator();
    public void processSubmissions(String zipFilePath) {
        List<String> studentSubmissions = SubmissionExtractor.extractSubmissions(zipFilePath);
        for (String studentSubmission : studentSubmissions) {
            Submission.resetInstance(studentSubmission);
            AssignmentDetails result = this.processSubmission(studentSubmission);
            System.out.println(result.toString());
            pdf.generate(result);
        }
    }
}

Factory Pattern

The Factory Pattern is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created. It encapsulates the object creation process, enabling the system to be independent of how its objects are created, composed, and represented. The pattern is used in this project to create different subclasses of GradeTemplate.

Abstraction: The Factory<T> interface specifies the <T>createItems(List<Result> results) and the T createItem(Result result, int index) methods. Any Factory class which creates item lists or an item should implement these methods.

public interface Factory<T> {
    public abstract List<T> createItems(List<Result> results);
    public abstract T createItem(Result result, int index);
}

Realization: GradeFactory is a realization that provides the concrete implementation for creating subclasses of GradeTemplate.

public class GradeFactory extends AbstractGradeFactory {
    @Override
    public Grade createItem(Result result, int index) {
        switch (index) {
            case Constants.PROGRAM_GRADE_INDEX:
                return new ProgramGrade(result);
            case Constants.CHATBOT_GENERATOR_GRADE_INDEX:
                return new ChatBotGeneratorGrade(result);
            case Constants.CHATBOT_GRADE_INDEX:
                return new ChatBotGrade(result);
            case Constants.CHATBOT_PLATFORM_GRADE_INDEX:
                return new ChatBotPlatformGrade(result);
            case Constants.CHATBOT_SIMULATION_GRADE_INDEX:
                return new ChatBotSimulationGrade(result);
            default:
                throw new IllegalArgumentException("Unexpected index: " + index);
        }
    }
}

Template Pattern

The Template Pattern is a behavioral design pattern that defines the program skeleton of an algorithm in an operation, deferring some steps to subclasses. It lets subclasses redefine certain steps of an algorithm without changing its structure. This pattern is particularly useful when multiple classes share a common algorithm structure but differ in specific steps. The template is used in the project to define a template for each type of grade to be made.

Abstraction: GradeTemplate is the abstract class specifying the shared details of each specific grade. Each subclass of the template will inherit all its state and methods and will be able to slightly override them.

package com.gophers.structures.grades;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import com.gophers.interfaces.Grade;

public abstract class GradeTemplate implements Grade {
    protected Map<String, Integer> testMarks;
    protected Map<String, Boolean> feedbackMap;
    private int totalMarks;
    private int marksEarned;

    public GradeTemplate(Result result, int totalMarks) {
        this.feedbackMap = new HashMap<String, Boolean>();
        this.totalMarks = totalMarks;
        this.allocateWeightings();
        this.allocateFeedback();
        this.setMarksEarned(result);
    }

    private void setMarksEarned(Result result) {
        this.marksEarned = result.wasSuccessful() ? totalMarks :

Clone this wiki locally