[[view-model-interface]]
= `ViewModel` interface

:Notice: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at. http://www.apache.org/licenses/LICENSE-2.0 . Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR  CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
:page-partial:


The most flexible approach to implement a view model is to implement the xref:refguide:applib:index/ViewModel.adoc[ViewModel] interface.

This defines a single method, `viewModelMemento()`, which returns a String representation of the object's state.
Or, it could return be a handle to its state if the state is actually stored elsewhere, eg in an external database.

The corollary is that the view model must also define a constructor whose first parameter is a `String`.
This constructor can optionally take additional injected services, which the view model can use to initialize itself (eg look up from the external database, if required).

For example:

[source,java]
.CompareCustomers.java, using ViewModel interface
----
@DomainObject
public class CompareCustomers implements ViewModel {    // <.>

    public CompareCustomers(
            String memento,                                                 // <.>
            CustomerRepository customerRepository                           // <.>
    ) {
        customer1 = customerRepository.findByRef(memento.split(":")[0]);    // <.>
        customer2 = customerRepository.findByRef(memento.split(":")[1]);    // <3>
    }

    public String viewModelMemento() {
        return getCustomer1().getRef() + ":" + getCustomer2().getRef();     // <.>
    }

    @Getter @Setter
    Customer customer1;

    @Getter @Setter
    Customer customer2;

    public String getCustomer1Name() {
        return getCustomer1().getName();
    }

    public String getCustomer2Name() {
        return getCustomer2().getName();
    }

    ...
}
----
<.> View model's state as originally returned by `viewModelMemento()` (below); mandatory
<.> Injected domain services; optional
<.> Unpacks the memento and uses it to restore state
<.> Encodes the current state into a string



